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

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

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面