PHP Object Assignment vs Cloning

前端 未结 7 1269
后悔当初
后悔当初 2020-11-29 05:34

I know this is covered in the php docs but I got confused with this issue .

From the php docs :

$instance = new SimpleClass();
$assigned   =  $ins         


        
7条回答
  •  旧时难觅i
    2020-11-29 06:03

    Objects are abstract data in memory. A variable always holds a reference to this data in memory. Imagine that $foo = new Bar creates an object instance of Bar somewhere in memory, assigns it some id #42, and $foo now holds this #42 as reference to this object. Assigning this reference to other variables by reference or normally works the same as with any other values. Many variables can hold a copy of this reference, but all point to the same object.

    clone explicitly creates a copy of the object itself, not just of the reference that points to the object.

    $foo = new Bar;   // $foo holds a reference to an instance of Bar
    $bar = $foo;      // $bar holds a copy of the reference to the instance of Bar
    $baz =& $foo;     // $baz references the same reference to the instance of Bar as $foo
    

    Just don't confuse "reference" as in =& with "reference" as in object identifier.

    $blarg = clone $foo;  // the instance of Bar that $foo referenced was copied
                          // into a new instance of Bar and $blarg now holds a reference
                          // to that new instance
    

提交回复
热议问题