PHP Object cloning using clone keyword and __clone() magic method

Feb 17, 2014, by admin

Object cloning or clone of an object means to create a duplicate of an object.
With regular variables $var1 = $var2 means that a new variable $var1 created and have the value of $var2 that means 2 variables created.

With objects $obj2 = $obj1 does not mean that a new object i.e. $obj2 get created.

When we execute $obj2 = $obj1, the reference of $obj1 is assigned to $obj2. This means that $obj1 and $obj2 point to the same memory space.

So assigning other variables to an object will not actually copy the object, it will simply create a new reference to the same object. In order to truly copy an object, we must use the clone keyword.
<?php
 
class House {
    private $room_name;
 
    public function setRoomName($room_name) {
        $this->room_name = $room_name;
    }
 
    public function getRoomName() {
        return $this->room_name;
    }
}
 
$obj1 = new House();
$obj1->setRoomName(“Bedroom”);
 
$obj2 = $obj1; //only reference or memory assigned
 
$obj2->setRoomName(“Dining Room”);
 
echo $obj1->getRoomName();
echo $obj2->getRoomName();
 
?>

Both will return “Bedroom”

Therefore, to create a new $obj2 object we must “clone” an object to create a new object.
<?php
    $obj2 = clone $obj1;
?>

After the above line is executed $obj2 with a new memory space is created with the data members having the same value as that of $obj1. This is also referred to as shallow copy.

However, this technique will not work with a class that has a data member which is an object of another class (i.e object of an object technique is used). In such a scenario, the cloned object continues to share the reference of the data member object of the class that was cloned.

For resolving this we need to use the concept of ‘deep copy’ as opposed to ‘shallow copy’. To implement this you should implement the magic method __clone().
<?php
 
class House {
    private $room_name;
 
    public function setRoomName($room_name) {
        $this->room_name = $room_name;
    }
 
    public function getRoomName() {
        return $this->room_name;
    }
 
    public function __clone() {
        $obj = new House();
        $obj->setRoomName($this->room_name);
        return $obj;
    }
 
}
 
$obj1 = new House();
$obj1->setRoomName(“Bedroom”);
 
$obj2 = clone $obj1; //new object $obj2
 
$obj2->setRoomName(“Dining Room”);
 
echo $obj1->getRoomName();
echo $obj2->getRoomName();
 
?>

So, the __clone() magic method allows developers to implement a deep copy of an object when it is cloned.

PHP first performs a shallow clone and the calls the __clone() method on the new object, if it exists, to complete the cloning process.