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.
clone creates a new object instance__clone() runs only on the cloned objectWhen an object is cloned, PHP performs a shallow copy. This means primitive values are copied, but object references remain shared unless handled inside __clone().
// 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);
?>
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.
Think of cloning like photocopying a document and writing notes only on the copy — the original remains unchanged.
__clone()Car class with brand, model, and features(Clone) to the brand using __clone()