In PHP, how do I deep copy objects with SPL?

In PHP, you can use the Standard PHP Library (SPL) to create deep copies of objects. One common way to achieve this is by implementing the `Serializable` interface, which allows you to define how your object should be serialized and unserialized. Below is an example demonstrating how to deep copy objects using SPL.

<?php class Person implements Serializable { public $name; public $age; public $friends; public function __construct($name, $age) { $this->name = $name; $this->age = $age; $this->friends = []; } public function addFriend(Person $friend) { $this->friends[] = $friend; } public function serialize() { return serialize([$this->name, $this->age, $this->friends]); } public function unserialize($data) { list($this->name, $this->age, $this->friends) = unserialize($data); } public function __clone() { // Deep copy the friends array foreach ($this->friends as $index => $friend) { $this->friends[$index] = clone $friend; } } } // Example Usage $john = new Person("John", 30); $mary = new Person("Mary", 28); $john->addFriend($mary); // Create a deep copy of John $johnCopy = clone $john; // Modifying the copy's name $johnCopy->name = "John Copy"; // Adding a new friend to the copied object $johnCopy->addFriend(new Person("Alice", 25)); // Original object remains unchanged echo $john->name; // Outputs: John echo $johnCopy->name; // Outputs: John Copy echo count($john->friends); // Outputs: 1 echo count($johnCopy->friends); // Outputs: 2 ?>

PHP deep copy SPL Serializable objects