Object Cloning in PHP

  • Avinash
  • 2
  • Nov 04, 2011
  • Tutorial

Object cloning is just like create an exact copy of an object from one object.

Cloning of an object is done using the keyword clone. So when you try to clone the object then it will call the __clone() method of the class if possible.

We can not call __clone() directly from any object.

How to Clone an Object

$cloned_obj = clone $object;
  $cloned_obj = clone $object;

Note: We can not call __clone() directly from any object.

Cloning an obejct will create a exact copy of the source object with all properties. In that case is any property is defined with reference then cloned object will have same value with reference.

Change Properties on Cloning

So what if you want to change the properties of the cloned object? PHP has one magic method __clone() which will call when you clone the object. It will call cloned object’s __clone() method.

So in this __clone() method we can alter the properties of the cloned object.

Another Way to Create a Copy of Class

PHP has another inbuilt function which help us to create an alias of the class. The aliased class will be exactly same as original class.

How to Use?

bool class_alias ($original_class , string $alias_class )
  bool class_alias ($original_class , string $alias_class )

This function takes two parameter, from where first parameter will be a object on an original class of which we want to create an object and second parameter must be passed as a string and it is determined as the name of the aliased object.

// This is the original class class original_class { } // Creating an alias of an original class class_alias("original_class", "aliased_class"); // Creating an object of both classes $a = new original_class; $b = new aliased_class;
  // This is the original class
  class original_class { }

  // Creating an alias of an original class
  class_alias("original_class", "aliased_class");

  // Creating an object of both classes
  $a = new original_class;
  $b = new aliased_class;

Related Posts

Written by Avinash

Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.

View all posts by:

  • http://erosbence.blogspot.om crystal88_

    cool, but the post discusses two different topics: object cloning and class aliasing. I would like it better if you would point out that these are very different things, the first operates on objects, the second operates on classes. This way it can be confusing for newbie PHP developers who possibly don’t have a solid understanding of OOP yet.

  • Pingback: Why We Clone the Objects in PHP | Expert PHP Developer