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

In PHP, you can copy objects in several ways depending on whether you want a shallow copy or a deep copy. Here’s a guide on how to do both.

Keywords: PHP, object copying, shallow copy, deep copy, programming.
Description: Learn how to copy objects in PHP effectively, understanding the difference between shallow and deep copies.
<?php class Person { public $name; public $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } } // Shallow copy $person1 = new Person("John", 30); $person2 = $person1; // This creates a shallow copy (both variables point to the same object) // Deep copy $person3 = new Person($person1->name, $person1->age); // This creates a new instance with the same values // Testing the copies $person2->name = "Doe"; // Changes person2's name will also affect person1 echo $person1->name; // Outputs: Doe $person3->name = "Smith"; // Changes person3's name won't affect person1 echo $person1->name; // Outputs: Doe ?>

Keywords: PHP object copying shallow copy deep copy programming.