php 如何在没有引用的情况下复制对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4123571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a copy of an object without reference?
提问by acm
It is well documented that PHP5 OOP objects are passed by referenceby default. If this is by default, it seems to me there is a no-default way to copy with no reference, how??
PHP5 OOP对象默认是通过引用传递的,这是有据可查的。如果这是默认设置,在我看来,没有默认的复制方式没有参考,如何?
function refObj($object){
foreach($object as &$o){
$o = 'this will change to ' . $o;
}
return $object;
}
$obj = new StdClass;
$obj->x = 'x';
$obj->y = 'y';
$x = $obj;
print_r($x)
// object(stdClass)#1 (3) {
// ["x"]=> string(1) "x"
// ["y"]=> string(1) "y"
// }
// $obj = refObj($obj); // no need to do this because
refObj($obj); // $obj is passed by reference
print_r($x)
// object(stdClass)#1 (3) {
// ["x"]=> string(1) "this will change to x"
// ["y"]=> string(1) "this will change to y"
// }
At this point I would like $x
to be the original $obj
, but of course it's not. Is there any simple way to do this or do I have to code something like this
在这一点上,我想$x
成为原来的$obj
,但当然不是。有什么简单的方法可以做到这一点,或者我是否必须编写这样的代码
回答by Treffynnon
<?php
$x = clone($obj);
So it should read like this:
所以它应该是这样的:
<?php
function refObj($object){
foreach($object as &$o){
$o = 'this will change to ' . $o;
}
return $object;
}
$obj = new StdClass;
$obj->x = 'x';
$obj->y = 'y';
$x = clone($obj);
print_r($x)
refObj($obj); // $obj is passed by reference
print_r($x)
回答by lonesomeday
To make a copy of an object, you need to use object cloning.
要制作对象的副本,您需要使用对象克隆。
To do this in your example, do this:
要在您的示例中执行此操作,请执行以下操作:
$x = clone $obj;
Note that objects can define their own clone
behaviour using __clone()
, which might give you unexpected behaviour, so bear this in mind.
请注意,对象可以使用 定义自己的clone
行为__clone()
,这可能会给您带来意想不到的行为,因此请记住这一点。