PHP Clone Objects:
Meaning of clone is that make multiple identical copies of the original one, the process of cloning in PHP 5 is quite different from PHP 4, in the earlier version of PHP all we need to do is to assign an object to another object. But in the latest version of PHP, clone construct along with a magic method is used to control the cloning process.
A clone object is created by using clone keyword which is called implicitly, and it is not possible to call the method explicitly. When an object is cloned a shallow copy of the original object is created.
After the creation of cloned object, if a __clone() method is defined, __clone() method of the newly created object is called, to change any properties which is need to be changed.
Example:
<?php
class
A{ public $var1; static $var2=0; public function __construct(){ $this->var1=++self::$var2;} public function __clone(){ $this->var1=++self::$var2;}}class
B{ public $obj1; public $obj2; function __clone(){ $this->obj1=$this->obj2;}}$objA
=new B();$objA
->obj1=new A;$objA
->obj2=new A;$objB
=clone $objA;print_r(
$objA);print_r(
$objB);?>
Output:
Actual Object is:
B Object ( [obj1] => A Object ( [var1] => 1 ) [obj2] => A Object ( [var1] => 2 )
)
Clone Object is:
B Object ( [obj1] => A Object ( [var1] => 2 ) [obj2] => A Object ( [var1] => 2 )
)
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.