php - PHP 中的对象复制与克隆

标签 php object clone

考虑以下几点:

$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/

相关文章:

extjs - 如何克隆 extjs 存储并将其用于多个网格

database - MSTest 单元测试和数据库访问,无需接触实际数据库

php - 将 $_GET-vars 添加到重写的 URL

php - 图片上传导致PDF库出错

php - 正则表达式和可分性

javascript - 创建多个对象数组

c# - Bitmap.Clone() 和 new Bitmap(Bitmap) 有什么区别?

php - 从数组中提取变量对性能有影响吗?

arrays - 如何将像这样的数组 ["John,Doe,11222019", "Mark,King,11232019", "Angle,Darma,11242019"] 转换为哈希 Ruby 数组

javascript - 在 JavaScript 中访问对象成员的有效方法