This article demonstrates how to create a copy of an object in PHP.

1. Using clone operator

In PHP, objects are passed by reference. To make a shallow copy of the object, you can clone it using the clone operator. The clone operator performs a shallow copy of all an object’s properties, but any references to other objects will remain references. In shallow copy, if the property is of scalar type, the value is copied; if the property value is a reference to another object, the reference is copied, hence referring to the same instance. If either of these objects is changed, the change is reflected in the others.

 
You can use the $object_copy = clone $object; syntax to create a shallow copy of an object. The following example demonstrates its usage:

Download  Run Code

Output:

stdClass Object
(
    [x] => 0
    [y] => 0
    [z] => 0
)

2. Using __clone() function

If your object holds a reference to another object, you can define the __clone() function to additionally call the clone operator on each of the objects. If done correctly, this will result in a deep copy of an object. The following example, taken from the PHP Object Cloning documentation, demonstrates the use of the __clone() function to facilitate necessary replication of the parent object’s properties with the clone operator.

Download  Run Code

Output:

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
        )
)

 
Note that the object’s __clone() function is invoked only if it is defined. Unlike other programming languages, __clone() method does not override the default cloning process. It will be invoked after cloning is done by the clone operator to allow any further changes to the copied properties.

That’s all about creating a copy of an object in PHP.