skip to Main Content
+91-9755185946 | +91-7879411522 / 9755185946 | info@webnexttechnology.com

Object Cloning in PHP

If you will directly copy objects in php, then it will copy by reference, not by value. Means if you will change main object data then copied object will be affected. Also if you will change value of the copied object then main object value will be changed. So if you want to create copy of the object which should never referenced to original object then you can take help of object cloning in php. In this tutorial we will explore what is usual object copy by reference and then object cloning. Also in end of this tutorial we will use __clone magic method to customize object cloning process in php.

Object copy or by reference copy

class test
{
public $a;
private $b;
function __construct($a, $b)
{
$this->a = $a;
$this->b = $b;
}
}
$a = new test("ankur" , "techflirt");
$b = $a; //Copy of the object
$a->a = "no Ankur";
print_r($a);
print_r($b);

Out Put:

test Object
(
    [a] => no Ankur
    [b:test:private] => techflirt
)
test Object
(
    [a] => no Ankur
    [b:test:private] => techflirt
)

Implementation of Object Cloning

class test
{
public $a;
private $b;
function __construct($a, $b)
{
$this->a = $a;
$this->b = $b;
}
}
$a = new test("ankur" , "techflirt");
$b = $a; //Copy of the object
$c = clone $a; //clone of the object
$a->a = "no Ankur";
print_r($a);
print_r($b);
print_r($c);

OutPut

test Object
(
    [a] => no Ankur
    [b:test:private] => techflirt
)
test Object
(
    [a] => no Ankur
    [b:test:private] => techflirt
)
test Object
(
    [a] => ankur
    [b:test:private] => techflirt
)
test Object
(
    [a] => no Ankur
    [b:test:private] => techflirt
)

Object cloning with magic method __clone

class test
{
public $a;
private $b;
function __construct($a, $b)
{
$this->a = $a;
$this->b = $b;
}
function __clone()
{
$this->a = "c";
}
}
$a = new test("ankur" , "techflirt");
$b = $a; //Copy of the object
$c = clone $a; //clone of the object
$a->a = "no Ankur";
print_r($a);
print_r($b);
print_r($c);
print_r($a);

Out Put

test Object
(
    [a] => no Ankur
    [b:test:private] => techflirt
)
test Object
(
    [a] => no Ankur
    [b:test:private] => techflirt
)
test Object
(
    [a] => ankur
    [b:test:private] => techflirt
)
test Object
(
    [a] => no Ankur
    [b:test:private] => techflirt
)
Back To Top