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 行为吗?
对我来说,听起来 $object2
是对 $object1
的引用,而不是副本。 在更改内容之前克隆对象确实像副本一样。 这种行为与变量发生的情况不同,对我来说似乎不直观。
Consider the following:
$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) { }
Is it a normal PHP behavior that $object2
has a content identical to $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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,这很正常。在 PHP5 中,对象总是通过引用“分配”。要实际创建对象的副本,您需要
克隆
它。为了更正确,让我引用手册:
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:
这是正常的,我不会认为这是不直观的(对于对象实例):
将一个新的对象实例分配给
$object1
。将对象实例分配给
$object2
。将从现有对象实例克隆的新对象实例分配给
$object3
。如果不是这样,每次需要传递具体对象实例时,都需要通过引用传递它。这至少很麻烦,但 PHP 在版本 4 中这样做了(比较
zend.ze1_compatibility_mode
核心 )。那没有用。克隆允许对象指定其复制方式。
That's normal and I won't consider this unintuitive (for object instances):
Assigns a new object instance to
$object1
.Assigns the object instance to
$object2
.Assigns an new object instance cloned from an existing object instance to
$object3
.If it would not be that way, each time you need to pass a concrete object instance, you would need to pass it by reference. That's burdensome at least but PHP did so in version 4 (compare
zend.ze1_compatibility_mode
core ). That was not useful.Cloning allows the object to specify how it get's copied.
对象复制与对象克隆
现在克隆对象
object copy vs object clone
now clone of an object
php5中的对象本质上是指针,也就是说,一个对象变量只包含位于其他地方的对象数据的地址。赋值
$obj1 = $obj2
仅复制此地址,并不触及数据本身。这可能确实看起来违反直觉,但实际上它非常实用,因为您很少需要拥有该对象的两个副本。我希望 php 数组使用相同的语义。Objects in php5 are essentially pointers, that is, an object variable contains only an address of the object data located somewhere else. An assignment
$obj1 = $obj2
only copies this address and doesn't touch the data itself. This may indeed appear counterintuitive, but in fact it's quite practical, because you only rarely need to have two copies of the object. I wish php arrays used the same semantics.