I got a strange behaviour in PHP with arrays and objects, that I don't understand. Maybe you guys can help me with that.
Creating an array, copy it to another array, change a value in the 2nd array and everything is as expected:
$array1['john']['name'] = 'foo';
$array2 = $array1;
$array2['john']['name'] = 'bar';
echo $array1['john']['name']; // foo
echo $array2['john']['name']; // bar
Now, if I do this with objects in that array, the object in the copied array holds some kind of a reference?
$array3['john']->name = 'foo';
$array4 = $array3;
$array4['john']->name = 'bar';
echo $array3['john']->name; // bar
echo $array4['john']->name; // bar
I would have expected the same behaviour as in the 1st example and I cannot find anything about this in the php docs. Can somebody explain that to me or send me an link to where this is documented?
Thanks!
When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.(php.net/manual/en/language.oop5.basic.php)