PHP Clone Object

Summary: in this tutorial, you will learn how to copy objects using shallow copying, as well as using deep copying via PHP clone object.

Let’s start creating a simple Person class for the sake of demonstration.

Now, we can create some Person objects:

We’ve created two objects:  $p1 and $p2. Both  $p1 and  $p2 are references pointing to the different person objects.

PHP clone object - 2 separated objects


What will happen if we do the following:

Both  $p1 and  $p2 are now pointing to the same object. However the destructor of the $p2 is called because the object that  $p2 is pointing is no longer in used or out of scope.

PHP clone object - shallow copy

As we have seen, no real object was created when we assigned $p1 to $p2, only the reference was changed. The way that we’ve copied object is known as shallow copy.

To perform a deep copy that results in creating a new object, we use clone operator as follows:

When we execute the statement, the  $p2 reference is pointing to the newly created object. In addition, during the execution, the __clone() magic methods is invoked automatically.

We can add the __clone() magic methods to the Person class to see how it works.

You can download the PHP clone object script files via the following link:

PHP Clone Object (1584 downloads)

In this tutorial, we have discussed the differences between shallow copy and deep copy when we copy an object. We also showed you how to use the clone operator to perform a deep copy of an object.

  • Was this tutorial helpful ?
  • YesNo