search

Home  >  Q&A  >  body text

How to copy an object without a reference?

<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粉805922437P粉805922437462 days ago446

reply all(2)I'll reply

  • P粉038161873
  • P粉713846879

    P粉7138468792023-08-25 00:31:47

    <?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)

    reply
    0
  • Cancelreply