如何在没有参考的情况下复制对象? [英] How to make a copy of an object without reference?
本文介绍了如何在没有参考的情况下复制对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有据可查的是,PHP5 OOP 对象是通过引用传递的默认情况下.如果默认情况下是默认设置,那么在我看来,这是一种没有参考的无默认复制方式,怎么办?
It is well documented that PHP5 OOP objects are passed by reference by default. If this is by default, it seems to me there is a no-default way to copy with no reference, how??
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"
// }
在这一点上,我希望$x
是原始的$obj
,但是当然不是.有什么简单的方法可以做到这一点,还是我必须编写
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
推荐答案
<?php
$x = clone($obj);
所以它应该像这样:
<?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)
这篇关于如何在没有参考的情况下复制对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文