Object Cloning

Sometimes it might be necessary to make a copy of an object, say for backup purposes or when you don't want to effect the state of the original object.

 

To make a copy of an object the keyword clone is used.

 

Syntax:

$copyObject = clone $originalObject;

 

clone can also be used directly within a function's parentheses to pass a copy of the passed in object to the function. In this case $originalObject is left intact and myFunction() acts upon the clone:

 

myFunction(clone $originalObject);

 

 

Once the cloning is complete, if a __clone() method is defined, then the newly created object's __clone() method will be called from the original class, to allow any necessary properties that need to be changed. Also note, an object's __clone() method cannot be called directly.

 

  • clone copies all variables from first object to new object
  • then calls __clone() magic method, from the class it is copying from
    • akin to a constructor for the cloned object

 

In this example an object is instantiated and then assigned to a new object using the clone keyword. Finally, it uses the clone keyword within a function which makes a cloned copy of the passed in object for use within the function:

Save & refresh browser:

Original object Instantiated!
Clone 1 copied.
Clone 2 copied.
This function will firstly clone the object being passed in, it will then use the __clone() magic method in the class, and finally it will print this message.

Leave a Reply