Back to results for “OOP”
PHP › Magic Methods

How can __clone be used to customize what happens when an object is duplicated using PHP's clone keyword, particularly for handling deep copies of nested objects?

Advanced

Answer

By default, PHP's clone keyword creates a shallow copy of an object, meaning any properties that are themselves objects will still reference the exact same underlying object instance in both the original and the clone, and implementing the __clone magic method lets you customize this behavior, such as explicitly cloning nested objects as well, ensuring the resulting clone is genuinely independent of the original rather than unintentionally sharing internal object references.
class Order {
    public Customer $customer;
    public function __clone() {
        $this->customer = clone $this->customer;
    }
}
$original = new Order();
$copy = clone $original;
Real-world example A developer debugging an unexpected shared state issue discovers that cloning an Order object had left both the original and the clone pointing to the exact same underlying Customer object, and fixes it by implementing __clone to explicitly deep clone that nested property.

Common follow-ups: What is the difference between a shallow copy and a deep copy in this context?;Are there performance considerations when deep cloning objects with many nested relationships?