How to copy an object without a reference?
P粉805922437
2023-08-24 10:51:49
<p>It is well documented that PHP5 OOP objects are passed by reference by default. If this is the default, it seems to me that there is a non-default way to copy without a reference, how about that? ? </p>
<pre class="brush:php;toolbar:false;">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"
// }</pre>
<p>At this point I expected <code>$x</code> to be the original <code>$obj</code>, but of course it isn't. Is there any easy way to do this or do I have to write code like this</p>
To copy an object you need to use Object Clone一个>.
To do this in your example:
Note that objects can define their own
clone
behavior using__clone()
, which may give you unexpected behavior, so please keep this in mind.So it should be like this: