对象复制与PHP中的克隆 [英] Object copy versus clone in PHP

查看:85
本文介绍了对象复制与PHP中的克隆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

$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行为吗?

Is it a normal PHP behavior that $object2 has a content identical to $object1 ?

在我看来,$object2是对$object1的引用,而不是副本. 在更改内容之前克隆对象的行为确实类似于副本. 这种行为与变量发生的行为不同,并且对我来说似乎是不直观的.

To me it sound like $object2 is a reference to $object1 instead of a copy. Cloning the object before changing the content does act like a copy. This behavior is different than what happens with variables and seems unintuitive to me.

推荐答案

是的,这很正常.在PHP5中,对象始终通过引用 分配".要实际复制对象,您需要clone它.

Yes, that's normal. Objects are always "assigned" by reference in PHP5. To actually make a copy of an object, you need to clone it.

不过,为了更正确,让我引用手册:

To be more correct though, let me quote the manual:

从PHP5开始,对象变量不再包含该对象本身作为值.它仅包含一个对象标识符,该标识符使对象访问者可以找到实际的对象.当对象通过参数发送,返回或分配给另一个变量时,不同的变量不是别名:它们持有标识符的副本,该副本指向相同的对象.

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中的克隆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆