PHP Reference ยท Functions and Classes
PHP object cloning: clone and __clone()
Reference for PHP clone and __clone(): how objects are copied, shallow versus deep copies, cloning nested objects and arrays, readonly properties and pitfalls.
Assigning an object to another variable copies only the handle; both variables then point at the same object. The clone keyword creates a new object of the same class with the same property values. This copy is shallow: properties that hold objects still point at the same inner objects.
After copying, PHP calls the new object's __clone() method if the class defines one. That is where you make the copy deeper, for example by cloning nested objects.
$a = new stdClass; $a->n = 1; $b = clone $a; $b->n = 2; echo $a->n; // 1
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
$copy = clone $object; class C { public function __clone(): void { // runs on the NEW object after the shallow copy } }
Return value of clone: a new object of the same class, whose properties are copies of the original's values (objects as shared handles, arrays by value).
Errors: cloning a non-object throws Error. If __clone() is private or protected, clone from outside the class throws Error; this is how you forbid copying (singletons). Cloning an enum case also throws Error.
Usage notes
__clone()is called on the copy, not the original.$thisis the new object; you cannot access the original from inside it.- Deep copy recursively. Clone every object property that must be independent, including objects inside arrays: loop and clone each element.
- Arrays are values. An array property is copied, but objects stored in that array are still shared handles.
- Readonly properties. Before PHP 8.3
__clone()could not change readonly properties; since 8.3 it may reinitialize them once, which is how deep copies of readonly objects are written. - Immutable "with" methods build a changed copy. With readonly properties, create it with
new static(...)(or reinitialize inside__clone()in 8.3+), because a plainclonefollowed by assignment would hit the readonly rule. - Resources and references. Properties holding resources (file handles) are shared; properties bound by reference stay bound.
- Identity:
===compares object identity,==compares class and property values. See object comparison. - Deep copy trick:
unserialize(serialize($obj))makes a deep copy of serializable data, but it is slow and triggers magic methods. - Lazy copying does not exist: PHP copies all properties immediately.