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.
$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.
<?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;?>
Foo
is created.Foo
class.clone
.foo_resource
of $a
object.__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;?>
Lines 2–11: We define an example class Foo
.
Line 8: We reference the foo_ref_resource
property 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 Foo
class.
Line 15: We update the reference address in the foo_recource
of $a
object.
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.
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
clone
on a non-object variable will result in a fatal error.
Free Resources