How to clone an object in PHP

One cannot create a copy constructor in PHP as overloading of methods is not allowed. But to get a full replica of an object, we can use a keyword clone provided by PHP.

Syntax

$obj1 = clone $obj2;

Note: Cloning an object will create a shallow copy of it, and any property that is a reference will remain a reference in the copied object as well.

The method __clone is called after cloning the object with the keyword clone, and further changes can be achieved by defining the __clone method in the class.

Example

<?php
class Foo
{
var $foo_resource = "This is an example resource\n";
}
$a = new Foo;
$b = clone $a;
$a->foo_resource = "Assigned new resource\n";
echo "Original: " . $a->foo_resource;
echo "Cloned: " . $b->foo_resource;
?>
How to use keyword `clone` in PHP

Explanation

  • Lines 2–5: An example class Foo is created.
  • Line 7: We create a new object of Foo class.
  • Line 8: We show to create a shallow copy of an object using clone.
  • Line 9: We update the value of foo_resource of $a object.
  • The output from line 19 confirms that a separate copy was created and it remained intact after the original one was changed.

Example of __clone()

Now let’s see how to add the __clone() method to achieve custom functionality with the keyword clone.

<?php
class Foo
{
public $foo_ref_resource;
public function __clone()
{
$temp = $this->foo_ref_resource;
unset($this->foo_ref_resource);
$this->foo_ref_resource = $temp;
}
}
$ref_string = "Referenced Quotes\n";
$a = new Foo;
$a->foo_ref_resource = &$ref_string;
$b = clone $a;
$ref_string = "Assigned new resource\n";
echo "Original: " . $a->foo_ref_resource;
echo "Cloned: " . $b->foo_ref_resource;
?>
Changing properties after cloning

Explanation

  • Lines 2–11: We define an example class Foo.

  • Line 8: We reference the foo_ref_resource property in the __clone() method to create a copy of the referenced resource.

  • Line 13: We create a string variable.

  • Line 14: We create a new object of Foo class.

  • Line 15: We update the reference address in the foo_recource of $a object.

  • After creating a copy of the provided object on line 16, the __clone() method will be called.

  • Line 17: We assign a new value to the $ref_string.

  • Note: From lines 18 and 19, the output of the original string is changed because it is being accessed by reference while the cloned copy is not changed.

Conclusion

You can use the keyword clone to create a shallow copy of objects and implement __clone() in your class to further customize the copied properties.

Caution: Calling clone on a non-object variable will result in a fatal error.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved