Reader Level:

How to Make Clone Object in PHP

By Sharad Gupta on Mar 04, 2013
In this article I explain how to clone an object in PHP.


In this article, we will study cloning of objects, how to make a cloned object.

Creating a copy of an object with fully replicated properties is not always the intended behavior and the meaning of clone is that there exists multiple identical copies of an original one. A cloned object is created by using the clone keyword that is called implicitly, and it is not possible to call the method explicitly. So the term cloning means make a copy of an old object to a new variable but the clone method cannot be called directly. When we make a clone of an object it will be called to allow any change in the properties that need to change. If you want to implement a copy constructor in PHP, then you can use the clone method to implement the copy constructor in PHP.

In simple words, cloning creates a genuine copy of an object. Assigning an object to another variable does not create a copy, it creates a reference to the same memory location as the object. Cloning an object creates a "shallow" copy of the original object. What this means is that any properties that reference other variables will remain references to those variables and not copies of them.



class Myclass

{ static $instances=0;

public $instance;

function __construct()

{ $this->instance=++self::$instances;


function __clone()





class Baseclass


public $object1;

public $object2;

function __clone()


$this->object1=clone $this->object1;



$obj = new Baseclass();

$obj->object1=new Myclass();

$obj->objec21=new Myclass();

$obj2=clone $obj;

echo "<pre>";

print("Orignal object:\n");


print("clone object:\n");





Sharad Gupta
Sharad Gupta

I'm a Software developer working with different Microsoft technologies like ASP.NET 3.5/4.0, AJAX, JavaScript, J Query, Ms-access, SQL Server 2005/2008/2014,ADO.NET,Typescript also enamored to learn different Microsoft t... Read more



Custom Software Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.
Infragistics jQuery Controls

Trending up