PHP objects in array copy

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!


Objects by default are passed by reference. If you assign some scalar value or an array to other variable, it is cloned. If you assign the object, only the reference is copied but the object is not.

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.

From http://php.net/manual/en/language.oop5.basic.php

So, you need to call clone if you want another object.

$array4['john'] = clone $array3['john'];

Objects are passed by reference in php5 (wich is usually how you would want your objects passed), arrays are not.

Use clone http://php.net/manual/en/language.oop5.cloning.php

--edit just a sec too late :-) --


Try to use clone want you work with object.

Someone wrote a function for that, when objects are in array.

Here the link

链接地址: http://www.djcxy.com/p/57944.html

上一篇: 为什么这个Getter和Setter的行为如此呢?

下一篇: 数组副本中的PHP对象