← Back to Chapters

PHP OOP Clone Method

? PHP OOP Clone Method

? Quick Overview

The __clone() magic method in PHP is executed automatically when an object is duplicated using the clone keyword. It allows developers to customize how an object should behave after being copied.

? Key Concepts

  • clone creates a new object instance
  • __clone() runs only on the cloned object
  • Cloning is shallow by default
  • Nested objects must be manually copied

? Syntax & Theory

When an object is cloned, PHP performs a shallow copy. This means primitive values are copied, but object references remain shared unless handled inside __clone().

? View Code Example
// Demonstrates object cloning with __clone() magic method
name = $name;
$this->age = $age;
$this->friends = [];
}

public function addFriend($friend) {
$this->friends[] = $friend;
}

public function __clone() {
$this->name = $this->name . " (Clone)";
}
}

$original = new Person("Meghraj", 25);
$original->addFriend("Ravi");

$clone = clone $original;
$clone->addFriend("Sneha");

print_r($original);
print_r($clone);
?>

? Live Output / Explanation

The cloned object gets a modified name and a separate friends list. Adding a new friend to the clone does not affect the original object.

? Interactive Concept

Think of cloning like photocopying a document and writing notes only on the copy — the original remains unchanged.

? Use Cases

  • Creating template-based objects
  • Duplicating configuration objects safely
  • Prototyping similar objects

? Tips & Best Practices

  • Always handle nested objects explicitly
  • Use cloning when immutability is required
  • Modify only cloned properties inside __clone()

? Try It Yourself

  • Create a Car class with brand, model, and features
  • Clone the object and update features in the clone
  • Append (Clone) to the brand using __clone()
  • Verify original object remains unchanged