使用克隆的原因是 PHP 在处理对象时总是返回对象作为引用,而不是作为副本。
这就是为什么在将对象传递给函数时不需要用 & (引用)指定它:
function doSomethingWithObject(MyObject $object) { // it is same as MyObject &object
...
}
因此,为了获得对象副本,您必须使用 clone 关键字这是一个关于 php 如何处理对象以及 clone 做什么的示例:
class Obj {
public $obj;
public function __construct() {
$this->obj = new stdClass();
$this->obj->prop = 1; // set a public property
}
function getObj(){
return $this->obj; // it returns a reference
}
}
$obj = new Obj();
$a = $obj->obj; // get as public property (it is reference)
$b = $obj->getObj(); // get as return of method (it is also a reference)
$b->prop = 7;
var_dump($a === $b); // (boolean) true
var_dump($a->prop, $b->prop, $obj->obj->prop); // int(7), int(7), int(7)
// changing $b->prop didn't actually change other two object, since both $a and $b are just references to $obj->obj
$c = clone $a;
$c->prop = -3;
var_dump($a === $c); // (boolean) false
var_dump($a->prop, $c->prop, $obj->obj->prop); // int(7), int(-3), int(7)
// since $c is completely new copy of object $obj->obj and not a reference to it, changing prop value in $c does not affect $a, $b nor $obj->obj!