·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> php网站开发 >> php __clone需要注意的问题

php __clone需要注意的问题

作者:佚名      php网站开发编辑:admin      更新时间:2022-07-23
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;  }