dongquxiao8545 2013-06-22 18:31
浏览 48
已采纳

使用给定键将对象添加到数组

I have an class with a private array. When I import an file I add want to add the new object (which is created) to this array for further use. I have in the object a name which I want to use as key. So:

<?php
$object = new Object();
$object->Name = "test";

class OtherObject
{
   private $loaded_files = array();

   public function AddObject($fileObj)
   {
     echo count($this->loaded_files); //results 0
     $this->loaded_files[$fileObj->Name] = clone $fileObj;
     echo count($this->loaded_files); //results 0

     //array_push($this->loaded_files, clone $fileObj);
     //$this->loaded_files["hard-coded"] = clone $fileObj;
   }
}

$otherObject = new OtherObject();
$otherObject->AddObject($object);
?>

As you can see in my example I want to use the Name as key and clone the object so it will be put in the array. After investigation array_push() (so, no key) and hard coded key works fine, but the $fileObj->Name doesn't. Do anyone know how this is possible?

Edit: Changed the example code a little bit. This is not my production code. I expect I have one but it keep zero. Only when i use no key or an hard coded key, the object is appended.

  • 写回答

1条回答 默认 最新

  • dongting3135 2013-06-22 19:09
    关注

    Ok I found the problem. @Barmar, @AlexShesterov thanks for helping.

    The problem was it wasnt trimmed before added to the object. So after adding trim($value) all the elements the problem was solved and the element added to the array :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?