PHP
“
中,我们可以使用 =” “
和 clone”来拷贝对象。
“
用 =”实现通过引用来拷贝对象:
$rasmus = $zeev;
要拷贝对象的值,要使用 clone:
$rasmus = clone $zeev;
PHP 5 拷贝的是对象的引用而不是值。当把一个现存的对象指定给一个新变量时,新
变量中保存的只是这个现存对象的引用。而不管是通过新变最还是旧变量来访问这个对象,
都会得到相同的结果。
要想基于相同的内容创建包含独立值的技巧,可以使用另一种称为拷贝值的方式,
即使用 clone 关键字。否则,第二个变量中保存的将只是对第一个对象的引用。
克隆的过程中会把第一个对象中所有的属性都拷贝到第二个对象中。其中也包括属性
中保存的对象,所以克隆的对象不会与原始对象共享同一个引用。
然而,这通常不是人们所期望的行为。例如,我们考虑一下下面例子中保存着
Address 对象的聚合版本 Person。
使用一个聚合类:
classAddress {
protected$city;
protected$country;
publicfunctionsetCity($city) {$this->city =$city; }
publicfunctiongetCity() {return$this->city; }
publicfunctionsetCountry($country) {$this->country =$country; }
publicfunctiongetCountry() {return$this-> country;}
}
classPerson {
protected$name;
protected$address;
publicfunction__construct() {$this->address =newAddress; }
publicfunctionsetName($name) {$this->name =$name; }
publicfunctiongetName() {return$this->name; }
publicfunction__call($method,$arguments) {
if(method_exists($this->address,$method)) {