What is Php Object Cloning?
Note:-
(i) If you will directly copy objects in PHP, then it will copy by reference, not by value.
(ii) if you will change main object data then copied objects will be affected. Also if you will change the value of the copied object then the main object value will be changed.
So if you want to create a copy of the object which should never be referenced to original object then you can take help of object cloning in php.
Simple Object Copy
If you will directly copy objects in php, then it will copy by reference, not by value.
Example:-
<?php
class student {
public $stu_name = 'John';
}
$stu_obj1 = new student;
$stu_obj2 = $stu_obj1;
$stu_obj2->stu_name="Tony";
echo $stu_obj1->stu_name;
echo $stu_obj2->stu_name;
?>
Tony
In this eg. object $stu_obj1 after copying it to $stu_obj2, we have changed its object value $stu_name to “Tony”, and then we have printed both object value and found that $stu_obj2 has changes made in $stu_obj1. This is one of the very useful when you want an object by reference. But when we need object copy by value, So to overcome with this limitation PHP has provided features of object cloning separately.
Object Copy with clone keyword
Example:-
<?php
class student {
public $stu_name = 'John';
}
$stu_obj1 = new student;
$stu_obj2 = clone $stu_obj1;
$stu_obj2->stu_name="Tony";
echo $stu_obj1->stu_name;
echo $stu_obj2->stu_name;
?>
Tony
In this eg. object $stu_obj1 after copy it to $stu_obj2 with clone keyword, we have changed its object value $stu_name to “Tony”, and then we have print both object value and found that $stu_obj2 has changed and stu_obj1 not changed.
Object cloning with magic method __clone
<?php
class student {
public $stu_name = 'John';
function __clone()
{
$this->stu_name='Tony';
}
}
$stu_obj1 = new student;
$stu_obj2 = clone $stu_obj1;
echo $stu_obj1->stu_name;
echo $stu_obj2->stu_name;
?>
Tony
In this eg. object $stu_obj1 after copy it to $stu_obj2 with clone keyword, then _clone() method invoked, in this method we have changed $stu_name value to “Tony”, then we have print both object value and found that $stu_obj2 has changed and stu_obj1 not changed.
Note:- If you use clone keyword then you should use _clone() method also.