In PHP, the _ clone () php's _ clone () method is used to perform a shortest copy on an object instance. the basic value type in the object is the copy by passing the value, if the object member variable in the object is explicitly cloned without rewriting the _ clone method, the member variable is passed for reference replication, instead of generating a new object. as mentioned in the comments of Line 3
1
Balance = $ balance; 7} 8} 9 10 class Person {11 private $ id; 12 private $ name; 13 private $ age; 14 public $ account; 15 16 public function _ construct ($ name, $ age, Account $ account) {17 $ this-> name = $ name; 18 $ this-> age = $ age; 19 $ this-> account = $ account; 20} 21 22 public function setId ($ id) {23 $ this-> id = $ id; 24} 25 26 public function _ clone () {# Copy method, in which you can define the clone operation 27 $ this-> id = 0; 28 $ this-> ac Count = clone $ this-> account; # if this clause is not added, the account will be copied and referenced only in clone, the balance of one account is modified, and the other will also be modified 29} 30} 31 32 $ person = new Person ("peter", 15, new Account (1000 )); 33 $ person-> setId (1); 34 $ person2 = clone $ person; 35 36 $ person2-> account-> balance = 250; 37 38 var_dump ($ person, $ person2); 39 40?>
Output:
Object (Person) #1 (4) {["id": "Person": private] => int (1) ["name": "Person ": private] => string (5) "peter" ["age": "Person": private] => int (15) ["account"] => object (Account) #2 (1) {["balance"] => int (1000)} object (Person) #3 (4) {["id": "Person ": private] => int (0) ["name": "Person": private] => string (5) "peter" ["age": "Person ": private] => int (15) ["account"] => object (Account) #4 (1) {["balance"] => int (250 )}}