Object Cloning in PHP5
- Create a copy of an object with the replicated properties.But if we change the properties of one object after cloning, it should not affect the properties of another object.
Example:
class one{
public $var1;
public function __construct(){
}
}
class trial{
public $var;
public $obj;
public function __construct(){
}
}
$xObj1 = new trial;
$xObj1->var = 1;
$xObj1->obj = new One;
$xObj1->obj->var1 = 10;
$xObj2 = clone $xObj1;
Basically this line will create a clone object $xObj2 = clone $xObj1.
In the above example if we change the value of the $xObj1->var after cloning, it won’t affect the value of $xObj2->var. but if we change the value of $xObj1->obj->var1 after cloning, it will affect the $xObj2->obj->var1.Because it is a reference variable which points to the same location after we create the clone object.
To Solve the above problem we need to change the trial class like following.
class trial{
public $var;
public $obj;
public function __construct(){
}
public function __clone(){
$this->obj = clone($this->obj);
}
}
So we need to clone the properties which are references to others.
