How to copy an object without a reference?
P粉805922437
P粉805922437 2023-08-24 10:51:49
0
2
411
<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>
P粉805922437
P粉805922437

reply all(2)
P粉038161873

To copy an object you need to use Object Clone一个>.

To do this in your example:

$x = clone $obj;

Note that objects can define their own clone behavior using __clone(), which may give you unexpected behavior, so please keep this in mind.

P粉713846879
<?php
$x = clone($obj);

So it should be 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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!