Php Object Cloning

What is Php Object Cloning?

Object cloning is the act of making a copy of an object.

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

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;
?>
Output:- Tony
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

By default Object copy by reference but with the clone keyword we copy the object by value not by reference.
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;
?>
Output:- John
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

Magic method clone executes when object cloning is performed. As soon as php execute statement $stu_obj2 = clone $stu_obj1, __clone method invoked.


<?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;
?>
Output:- John
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.