How to Make Clone Object in PHP

Introduction

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.

Example

<?php

class Myclass

{ static $instances=0;

public $instance;

function __construct()

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

}

function __clone()

{

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

}

}

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_r($obj);

print("clone object:\n");

print_r($obj2);

?>

Output

clone-object-in-php.jpg


Similar Articles