默认情况下,PHP5 OOP objects are passed by reference有据可查。如果这是默认情况下,在我看来有没有默认的方式来复制没有参考,如何?如何制作一个没有参考的对象的副本?
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
,但当然不是。有没有简单的方法来做到这一点还是我的代码的东西like this
很高兴它有帮助。 lonesomeday对于__clone()魔术方法提供了一个很好的观点,一些类也可能正在实现,值得注意。 – Treffynnon 2010-11-08 12:12:18