Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/visual-studio/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在php中将对象添加到数组中?_Php_Oop - Fatal编程技术网

如何在php中将对象添加到数组中?

如何在php中将对象添加到数组中?,php,oop,Php,Oop,我想在一个对象(处理程序)中创建一个数组,在PHP中保存一系列对象(主题)。数组是处理程序的一个属性,我有一个创建新主题的方法 class MyHandler ( $TheList = array(); $TempSubject = object; // class subject public function AddNewSubject($information) { $TempSubject = new subject($information); $This

我想在一个对象(处理程序)中创建一个数组,在PHP中保存一系列对象(主题)。数组是处理程序的一个属性,我有一个创建新主题的方法

class MyHandler (
  $TheList = array();
  $TempSubject = object; // class subject

  public function AddNewSubject($information) {
    $TempSubject = new subject($information);
    $This->TheList [] = $TempSubject;
  }
)

如果我如上所述创建一个新主题,那么信息持久化对象是在
MyHandler
中持久化还是在
AddNewSubject
结束后丢失?我是PHP新手,所以请对任何错误发表评论。

它将持续存在,但您有一个输入错误
$This
。。应该是
$this

您应该使用array\u push方法,请在此处进行检查:

要回答您的问题,请选择“是”,对象将保留在类中

class MyHandler (
     public $TheList = array();

     public function AddNewSubject($information) {
          $this->TheList[] = new subject($information);
     }
)

对象方法中的
$TempSubject
只是一个临时变量。但是,如果要这样定义函数:

public function AddNewSubject($information) {
  $this->TempSubject = new subject($information);
  $this->TheList [] = $this->TempSubject;
}
public function AddNewSubject($information) {
  $this->TempSubject = new subject($information);
  $this->TheList [] =& $this->TempSubject;
}
然后对象的属性(
$this->TempSubject
)将每次更新,但该对象的副本将存储在
$this->TheList

最后,如果要像这样定义函数:

public function AddNewSubject($information) {
  $this->TempSubject = new subject($information);
  $this->TheList [] = $this->TempSubject;
}
public function AddNewSubject($information) {
  $this->TempSubject = new subject($information);
  $this->TheList [] =& $this->TempSubject;
}
您会发现
$this->list
将包含对同一对象的引用列表,每次调用该函数时都会覆盖该列表


我希望这能有所帮助。

为什么<代码>$array[]=“新值”也是这样thing@xil3
$array[]
array\u push($array,?)的别名
所以是的,它是相同的。事实上,我知道这是什么,但我的观点是,这个答案并没有给这个问题增加任何价值。哦,孩子!搜索并替换!:)