Object Cloning in PHP

Cloning in PHP

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

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

We can not call [code]__clone()[/code] directly from any object.

How to Clone an Object

[cc lang=”php”]
$cloned_obj = clone $object;
[/cc]

Note: We can not call [code]__clone()[/code] 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?

[cc lang=”php”]
bool class_alias ($original_class , string $alias_class )
[/cc]

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.

[cc lang=”php”]
// 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;
[/cc]

Shares:
  • crystal88_
    November 8, 2011 at 3:24 pm

    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.

    Reply
  • crystal88_
    December 20, 2019 at 2:52 pm

    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.

    Reply
  • […] same question in their mind. In one of my earlier post I have explined that, creating a copy with clone keyword will make and object copy of the the class. Just like creating another set of varibales.Why we use […]

    Reply

Leave a Reply

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