PHP 5 Tutorial - __clone Magic Method

In PHP 5 when you assign one object to another object creates a reference copy and does not create duplicate copy. This would create a big mess as all the object will share the same memory defined for the object. To counter this PHP 5 has introduced clone method which creates an duplicate copy of the object. __clone magic method automatically get called whenever you call clone methods in PHP 5.





Example - Without Object Cloning

< ?
class Animal
{
   public $name;
   public $legs;
 
   function setName($name)
   {
	$this->name = $name;
   }
 
   function setLegs($legs)
   {
	$this->legs = $legs;
   }
}
 
$tiger = new Animal();
$tiger->name = "Tiger";
$tiger->legs = 4;
 
$kangaroo = $tiger;
$kangaroo->name = "Kangaroo";
$kangaroo->legs = 2;
 
echo $tiger->name."---".$tiger->legs;
echo "<br />".$kangaroo->name."---".$kangaroo->legs;
?>

Output:
Kangaroo—2
Kangaroo—2

Explanation:

Example - Above Example With clone Function

< ?
class Animal
{
   public $name	;
   public $legs;
 
   function setName($name)
   {
	$this->name = $name;
   }
 
   function setLegs($legs)
   {
	$this->legs = $legs;
   }
 
   function __clone()
   {
	echo "<br />Object Cloning in Progress";
   }
}
 
$tiger = new Animal();
$tiger->name = "Tiger";
$tiger->legs = 4;
 
$kangaroo = clone $tiger;
$kangaroo->name = "Kangaroo";
$kangaroo->legs = 2;
 
echo "<br />".$tiger->name."---".$tiger->legs;
echo "<br />".$kangaroo->name."---".$kangaroo->legs;
?>

Output:
Object Cloning in Progress
Tiger—4
Kangaroo—2

Explanation:

Similar Posts

Custom Search

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

very nice tutorial and explanation. i helps us a lot.

Thanks very much
Gurpreet

Leave a comment

(required)

(required)