Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Object Assignment vs Cloning

Tags:

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

From the php docs :

$instance = new SimpleClass(); $assigned   =  $instance; $reference  =& $instance; $instance->var = '$assigned will have this value'; $instance = null; // $instance and $reference become null var_dump($instance); var_dump($reference); var_dump($assigned); ?> 

The above example will output:

NULL NULL object(SimpleClass)#1 (1) { ["var"]=>  string(30) "$assigned will have this value" } 

OK so I see that $assigned survived the original object ($instance) being assigned to null, so obviously $assigned isn't a reference but a copy of $instance.

So what is the difference between

 $assigned = $instance  

and

 $assigned = clone $instance 
like image 817
Joel Blum Avatar asked Jun 03 '13 09:06

Joel Blum


People also ask

What is object cloning in PHP?

The clone keyword is used to create a copy of an object. If any of the properties was a reference to another variable or object, then only the reference is copied. Objects are always passed by reference, so if the original object has another object in its properties, the copy will point to the same object.

Which is the correct syntax of creating clone object?

An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). $copy_of_object = clone $object; When an object is cloned, PHP will perform a shallow copy of all of the object's properties. Any properties that are references to other variables will remain references.


1 Answers

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 
like image 104
deceze Avatar answered Oct 20 '22 01:10

deceze