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
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?