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:

<?php
	class MyObject {

		public $name = "Original";
		static $instances = 0;
		public $instance;

		public function __construct(){
			echo "$this->name object Instantiated!<br>";
		}

		public function __clone(){
			$this->instance = ++self::$instances;
			echo "Clone " . $this->instance . " copied.<br>";
		}
	}

	function myFunction(){
		echo "This function will firstly clone the object being passed in, ";
		echo "it will then use the __clone() magic method ";
		echo "in the original object's class, ";
		echo "and finally it will print this message.<br>";
	}

	$originalObject = new MyObject;

	$copyObject = clone $originalObject;

	myFunction(clone $copyObject);
?>

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