可能的重复:
PHP 中的对象克隆是什么? https://stackoverflow.com/questions/2144506/what-is-object-cloning-in-php
我正在研究一个经常使用“clone”关键字的现有框架,不确定这是否是一个好主意?我真的不明白使用“克隆”关键字的必要性。
例如看看这个编码
i.e
public function getStartDate ()
{
return clone $this->startDate;
}
对我来说这个函数应该像下面这样,我不认为克隆的需要。
public function getStartDate ()
{
return $this->startDate;
}
使用克隆的原因是 PHP 在处理对象时总是返回对象作为引用,而不是作为副本。
这就是为什么当将对象传递给函数时,您不需要使用 & (引用)指定它:
function doSomethingWithObject(MyObject $object) { // it is same as MyObject &object
...
}
因此,为了获得对象副本,您必须使用clone关键字
这是一个关于 php 如何处理对象以及克隆的作用的示例:
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!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)