I have an object (Two) which holds an object (One) and an array:
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;
}
}
Why I can manipulate the returned object, but cannot manipulate the returned array:
$two = new Two();
$two->getObject()->a = 'a';
$two->getArray()[] = 'b'; // Does not work!
$two->array[] = 'c';
var_dump($two);
Result (b
is missing in the array):
// class test\Two (2) {
// protected $object =>
// class test\One (1) { public $a => string(1) "a" }
// protected $array => array(1) { [0] => string(1) "c" }
// }
What makes the difference, as I think there's returned a copy of the reference to the array itself, but not to its elements.
Thanks for your explanation! ;D