考虑以下几点:
$object1 = new stdClass();
$object2 = $object1;
$object3 = clone $object1;
$object1->content = 'Ciao';
var_dump($object1);
// Outputs object(stdClass)#1 (1) { ["content"]=> string(4) "Ciao" }
var_dump($object2);
// Outputs object(stdClass)#1 (1) { ["content"]=> string(4) "Ciao" }
var_dump($object3);
// Outputs object(stdClass)#2 (0) { }
$object2
的内容与 $object1
相同,这是正常的 PHP 行为吗?
在我看来,$object2
是对 $object1
的引用,而不是副本。
在更改内容之前克隆对象确实像复制一样。
这种行为与变量发生的行为不同,对我来说似乎不直观。
最佳答案
是的,这很正常。在 PHP5 中,对象总是通过引用“分配”。要真正复制一个对象,您需要clone
它。
为了更正确,让我引用 the manual :
As of PHP5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.
关于php - PHP 中的对象复制与克隆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6972860/