How to clone an object in PHP
One cannot create a copy constructor in PHP as overloading of methods is not allowed. But to get a full replica of an object, we can use a keyword clone provided by PHP.
Syntax
$obj1 = clone $obj2;
Note: Cloning an object will create a shallow copy of it, and any property that is a reference will remain a reference in the copied object as well.
The method __clone is called after cloning the object with the keyword clone, and further changes can be achieved by defining the __clone method in the class.
Example
<?phpclass Foo{var $foo_resource = "This is an example resource\n";}$a = new Foo;$b = clone $a;$a->foo_resource = "Assigned new resource\n";echo "Original: " . $a->foo_resource;echo "Cloned: " . $b->foo_resource;?>
Explanation
- Lines 2–5: An example class
Foois created. - Line 7: We create a new object of
Fooclass. - Line 8: We show to create a shallow copy of an object using
clone. - Line 9: We update the value of
foo_resourceof$aobject. - The output from line 19 confirms that a separate copy was created and it remained intact after the original one was changed.
Example of __clone()
Now let’s see how to add the __clone() method to achieve custom functionality with the keyword clone.
<?phpclass Foo{public $foo_ref_resource;public function __clone(){$temp = $this->foo_ref_resource;unset($this->foo_ref_resource);$this->foo_ref_resource = $temp;}}$ref_string = "Referenced Quotes\n";$a = new Foo;$a->foo_ref_resource = &$ref_string;$b = clone $a;$ref_string = "Assigned new resource\n";echo "Original: " . $a->foo_ref_resource;echo "Cloned: " . $b->foo_ref_resource;?>
Explanation
-
Lines 2–11: We define an example class
Foo. -
Line 8: We reference the
foo_ref_resourceproperty in the__clone()method to create a copy of the referenced resource. -
Line 13: We create a string variable.
-
Line 14: We create a new object of
Fooclass. -
Line 15: We update the reference address in the
foo_recourceof$aobject. -
After creating a copy of the provided object on line 16, the
__clone()method will be called. -
Line 17: We assign a new value to the
$ref_string. -
Note: From lines 18 and 19, the output of the original string is changed because it is being accessed by reference while the cloned copy is not changed.
Conclusion
You can use the keyword clone to create a shallow copy of objects and implement __clone() in your class to further customize the copied properties.
Caution: Calling
cloneon a non-object variable will result in a fatal error.
Free Resources