In PHP, how do I deep copy objects in vanilla PHP?

In vanilla PHP, to deep copy objects, you can use the serialization and unserialization technique. This method creates a duplicate of the object, including its nested objects, enabling you to maintain the integrity of the original object without any references.

<?php class Address { public $street; public $city; public function __construct($street, $city) { $this->street = $street; $this->city = $city; } } class User { public $name; public $address; public function __construct($name, Address $address) { $this->name = $name; $this->address = $address; } } // Original object $originalAddress = new Address("123 Main St", "Anytown"); $originalUser = new User("John Doe", $originalAddress); // Deep copy $deepCopiedUser = unserialize(serialize($originalUser)); // Modifying the copied object $deepCopiedUser->address->street = "456 Another St"; // Original object remains unchanged echo $originalUser->address->street; // Outputs: "123 Main St" echo $deepCopiedUser->address->street; // Outputs: "456 Another St" ?>

PHP deep copy object copy PHP serialization PHP clone objects PHP