PHP中的__clone()
程序员文章站
2024-02-17 22:59:22
...
php的__clone()方法对一个对象实例进行的浅复制,对象内的基本数值类型进行的是传值复制,而对象内的对象型成员变量,如果不重写__clone方法,显式的clone这个对象成员变量的话,这个成员变量就是传引用复制,而不是生成一个新的对象.如第28行注释所说
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) } }