Cloning Objet in PHP | Object copy

Cloning object in PHP

Cloning Object in PHP

Object cloning is the process to create a copy of an object.

An object copy is created by using the magic method  __clone().

If you don't use the __clone() method, the internal objects of the new object will be references to the same object in memory as the internal objects of the original object that was cloned.
An object's _clone() method cannot be called directly. When an object is cloned, PHP will perform a shallow copy of all of the object's properties. Any properties that are references to other variables will remain references.

PHP clone object without reference:
<?php
class sample
{
 public $v1;
 private $v2;
 function __construct($v1,$v2)
 {
  $this->v1=$v1;
  $this->v2=$v2;
 }
}

$v1=new Sample("SoulCoder","S/W Dev");
$v2=$v1;#copy of object
$v1->v1="Shivam";
print_r($v1);
echo "<br>";
print_r($v2);

?>
Output:
sample Object ( [v1] => Shivam [v2:sample:private] => S/W Dev )
sample Object ( [v1] => Shivam [v2:sample:private] => S/W Dev )

All the above example show object copy js object by reference not by value. If you want object copy by value then this example will not work so to overcome this feature object cloning is introduced

We already have seen that object cloning is a copy of object by reference not by value but if we want to assign it by value then object cloning can be called. We implement object cloning by clone keyword.

Using Clone Object | PHP


Let us see the same above example using clone keyword :
<?php
class sample
{
 public $v1;
 private $v2;
 function __construct($v1,$v2)
 {
  $this->v1=$v1;
  $this->v2=$v2;
 }
}

$v1=new Sample("SoulCoder","S/W Dev");
$v2=$v1;#copy of object
$V3= clone $v1;
$v1->v1="Shivam";
print_r($v1);
echo "<br>";
print_r($v2);
echo "<br>";
print_r($V3);
?>
Output:
sample Object ( [v1] => Shivam [v2:sample:private] => S/W Dev )
sample Object ( [v1] => Shivam [v2:sample:private] => S/W Dev )
sample Object ( [v1] => SoulCoder [v2:sample:private] => S/W Dev )

In the above example, $V3 is a clone of $v1. So $V3 is completely separate from an object $v1 and $v2


Comments