时间:2021-07-01 10:21:17 帮助过:22人阅读
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() { #复制方法,可在里面定义再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) } }