众所周知,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"
// }
此时我希望$x
是原始的$obj
,但当然它并不是。是否有简单的方法来做到这一点,或者我必须编写像这样的代码呢?
__clone()
魔术方法,值得注意。 - Treffynnon