【发布时间】:2020-07-21 05:11:17
【问题描述】:
我有一个对象(二),其中包含一个对象(一)和一个数组:
class One {
public $a;
}
class Two {
public $object;
public $array;
public function __construct() {
$this->object = new One();
$this->array = [];
}
function getObject() {
return $this->object;
}
function getArray() {
return $this->array;
}
}
为什么我可以操作返回的对象,却不能操作返回的数组:
$two = new Two();
$two->getObject()->a = 'a';
$two->getArray()[] = 'b'; // Does not work!
$two->array[] = 'c';
var_dump($two);
结果(数组中缺少b):
// class test\Two (2) {
// protected $object =>
// class test\One (1) { public $a => string(1) "a" }
// protected $array => array(1) { [0] => string(1) "c" }
// }
有什么不同,因为我认为返回了对数组本身的引用的副本,而不是它的元素。
感谢您的解释! ;D
【问题讨论】:
-
“不起作用”是否有任何错误信息?
-
@Nico:不,但它不会被分配,正如您在转储字符串中看到的那样。
-
那么,是什么让您认为首先返回了引用?
-
对象是通过引用返回的,而数组不是。
标签: php