php __clone需要注意的问题

王朝学院·作者佚名  2016-05-25
窄屏简体版  字體: 小  |  中  |  大  |  超大  

php __clone需要注意的问题 当一个对象的属性是另外一个对象时,当有一个对象复制该对象时,当复制到这个属性(一个对象)时,只复制这个属性(对象)的引用,而不复制引用的对象。

class Account{ public $balance; function __construct($balance){ $this->balance=$balance; }}class Person{ PRivate $name; private $age; private $id; public $account; function __construct($name,$age,$account){ $this->name=$name; $this->age=$age; $this->account=$account; } function setId($id){ $this->id=$id; } function __clone(){ $this->id=0; }}$p1=new Person('tom', 33, new Account(200));$p1->setId(4);$p2=clone $p1;//给$p1充500 $p1->account->balance+=500;//结果$p2也得到了这笔钱print $p2->account->balance; //700

当创建一个新副本($p2)时,新对象($p2)的中所保存的引用指向的是$p1所引用的同一个$account对象.

如果不想对象属性在被复制之后被共享,可以显式地在__clone方法中复制指向的对象

function __clone(){ $this->id=0; $this->account=clone $this->account; }

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航