_ Clone () in PHP ()

Source: Internet
Author: User
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 )}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.