Share on Google+Share on Google+

PHP Clone Object

In this PHP tutorial, we will study about cloning of object, how to make a clone object, what are the process of cloning in PHP 5 and how is it different from PHP 4

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.



class A{

public $var1;

static $var2=0;

public function __construct(){


public function __clone(){


class B{

public $obj1;

public $obj2;

function __clone(){


$objA=new B();

$objA->obj1=new A;

$objA->obj2=new A;

$objB=clone $objA;

print("Actual Object is:<br/>");


print("<br/>Clone Object is:<br/>");




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 ) )



Posted on: March 5, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null