我在 PHP 中遇到了数组和对象的奇怪行为,我不明白。也许你们可以帮助我。
创建一个数组,将其复制到另一个数组,更改第二个数组中的值,一切都按预期进行:
$array1['john']['name'] = 'foo';
$array2 = $array1;
$array2['john']['name'] = 'bar';
echo $array1['john']['name']; // foo
echo $array2['john']['name']; // bar
现在,如果我对该数组中的对象执行此操作,复制的数组中的对象会保存某种引用吗?
$array3['john']->name = 'foo';
$array4 = $array3;
$array4['john']->name = 'bar';
echo $array3['john']->name; // bar
echo $array4['john']->name; // bar
我期望与第一个示例中的行为相同,但我在 php 文档中找不到任何有关此内容的信息。有人可以向我解释一下或者向我发送一个记录此内容的链接吗?
谢谢!
最佳答案
对象默认通过引用传递。如果将某个标量值或数组分配给其他变量,则会克隆它。如果分配对象,则仅复制引用,但不会复制对象。
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.
来自http://php.net/manual/en/language.oop5.basic.php
因此,如果您想要另一个对象,则需要调用clone
。
$array4['john'] = clone $array3['john'];
关于数组副本中的 PHP 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14172039/