PHP中的__clone()


php的__clone()方法對一個對象實例進行的淺復制,對象內的基本數值類型進行的是傳值復制,而對象內的對象型成員變量,如果不重寫__clone方法,顯式的clone這個對象成員變量的話,這個成員變量就是傳引用復制,而不是生成一個新的對象.如第28行注釋所說

 1  <?php
 2     class Account {
 3         public $balance;
 4         
 5         public function __construct($balance) {
 6             $this->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() {    #復制方法,可在里面定義再clone是進行的操作
27             $this->id = 0;
28             $this->account = clone $this->account;    #不加這一句,account在clone是會只被復制引用,其中一個account的balance被修改另一個也同樣會被修改
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  ?>

輸出:

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) } }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM