php __clone需要注意的问题

时间:2023-01-08 15:26:42

  当一个对象的属性是另外一个对象时,当有一个对象复制该对象时,当复制到这个属性(一个对象)时,只复制这个属性(对象)的引用,而不复制引用的对象。

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;

}