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);
?>
sample Object ( [v1] => Shivam [v2:sample:private] => S/W Dev )
<?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);
?>
sample Object ( [v1] => Shivam [v2:sample:private] => S/W Dev )
sample Object ( [v1] => SoulCoder [v2:sample:private] => S/W Dev )

Comments
Post a Comment
If you have any query, please let us know