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 :)

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题