Categories
PHP

Object Cloning in PHP

Object cloning is the act of making a copy of an object. Cloning in PHP is done by making a shallow copy of the object. This means that internal objects of the cloned object will not be cloned, unless you explicitly instruct the object to clone these internal objects too, by defining the magic method __clone().

In simple words,

Cloning is used to create a genuine copy of an object. Assigning an object to another variable does not create a copy – rather, it creates a reference to the same memory location as the object:

$o = new stdclass;
$o->a = 'b';
$o->b = 'c';

$o2 = $o;
$o2->a = 'd';

var_dump($o);
var_dump($o2);

$o3 = clone $o;
$o3->a = 'e';
var_dump($o);
var_dump($o3);

This example code will output the following:

object(stdClass)#1 (2) {
  ["a"]=>
  string(1) "d"
  ["b"]=>
  string(1) "c"
}
object(stdClass)#1 (2) {
  ["a"]=>
  string(1) "d"
  ["b"]=>
  string(1) "c"
}
object(stdClass)#1 (2) {
  ["a"]=>
  string(1) "d"
  ["b"]=>
  string(1) "c"
}
object(stdClass)#2 (2) {
  ["a"]=>
  string(1) "e"
  ["b"]=>
  string(1) "c"
}

If you don’t utilize the __clone method, the internal objects of the new object will be references to the same objects in memory as the internal objects of the original object that was cloned.

// in this example the internal member $_internalObject of both objects
// reference the same instance of stdClass in memory.
class CloneableClass
{
    private $_internalObject;

    public function __construct()
    {
        // instantiate the internal member
        $this->_internalObject = new stdClass();
    }
}

$classA = new CloneableClass();
$classB = clone $classA;

// in this exampe the internal member $_internalObject of both objects
// DON'T reference the same instance of stdClass in memory, but are inividual instances
class CloneableClass
{
    private $_internalObject;

    public function __construct()
    {
        // instantiate the internal member
        $this->_internalObject = new stdClass();
    }

    // on clone, make a deep copy of this object by cloning internal member;
    public function __clone()
    {
        $this->_internalObject = clone $this->_internalObject;
    }
}

$classA = new CloneableClass();
$classB = clone $classA;

Use cases for cloning would for instance be a case where you don’t want outside objects to mess with the internal state of an object.

Let’s say you have a class User with a internal object Address.

class Address
{
    private $_street;
    private $_streetIndex;
    private $_city;
    // etc...

    public function __construct( $street, $streetIndex, $city /* etc.. */ )
    {
        /* assign to internal values */
    }
}

class User
{
    // will hold instance of Address
    private $_address;

    public function __construct()
    {
        $this->_address = new Address( 'somestreet', '1', 'somecity' /* etc */ );
    }

    public function getAddress()
    {
        return clone $this->_address;
    }
}

For arguments sake, let’s say you don’t want outside objects to mess with the internal Address of User objects, but you do want to be able to give them a copy of the Address object. The above example illustrates this. The getAddress method returns a clone of the address object to calling objects. This means that if the calling object alters the Address object, the internal Address of User will not change. If you didn’t give a clone, then the outside object would be able to alter the internal Address of User, because a reference is given by default, not a clone.

An object copy is created by using the clone keyword (which calls the object’s __clone() method if possible).  An object’s __clone() method cannot be called directly.

$copy_of_object = clone $object;

Creating a copy of an object with fully replicated properties is not always the wanted behavior. If your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.

class SubObject
{
    static $instances = 0;
    public $instance;

    public function __construct() {
        $this->instance = ++self::$instances;
        echo "SubObject construct\n";
    }

    public function __clone() {
        $this->instance = ++self::$instances;
        echo "SubObject clone\n";
    }
}

class MyCloneable
{
    public $object1;
    public $object2;

    function __clone()
    {
        // Force a copy of this->object, otherwise
        // it will point to same object.
        $this->object1 = clone $this->object1;
        echo "MyCloneable clone\n\n";
    }
}

$obj = new MyCloneable();
echo "new MyCloneable() -- Done with MyCloneable \n\n";

echo "calling new SubObject() \n";
$obj->object1 = new SubObject();
echo "new SubObject() -- Done with SubObject1 \n";
echo "calling new SubObject() \n";
$obj->object2 = new SubObject();
echo "new SubObject() -- Done with SubObject2 \n\n";

echo "calling clone of MyCloneable object \n";
$obj2 = clone $obj;

print("Original Object:\n");
print_r($obj);

print("Cloned Object:\n");
print_r($obj2);

resulting to

new MyCloneable() -- Done with MyCloneable

calling new SubObject()
SubObject construct
new SubObject() -- Done with SubObject1
calling new SubObject()
SubObject construct
new SubObject() -- Done with SubObject2

calling clone of MyCloneable object
SubObject clone
MyCloneable clone

Original Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 1
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )
)

Cloned Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 3
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )
)
'Coz sharing is caring

By Swatantra Kumar

Swatantra is an engineering leader with a successful record in building, nurturing, managing, and leading a multi-disciplinary, diverse, and distributed team of engineers and managers developing and delivering solutions. Professionally, he oversees solution design-development-delivery, cloud transition, IT strategies, technical and organizational leadership, TOM, IT governance, digital transformation, Innovation, stakeholder management, management consulting, and technology vision & strategy. When he's not working, he enjoys reading about and working with new technologies, and trying to get his friends to make the move to new web trends. He has written, co-written, and published many articles in international journals, on various domains/topics including Open Source, Networks, Low-Code, Mobile Technologies, and Business Intelligence. He made a proposal for an information management system at the University level during his graduation days.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.