PHP克隆关键字

mah*_*n3d 5 php

可能重复:
什么是PHP中的对象克隆?

我正在研究一个使用"克隆"关键字的现有框架,不确定这是否是一个好主意?我真的不明白需要使用'clone'关键字.

例如,看看这个编码

  public function getStartDate ()
  {
    return clone $this->startDate;
  }
Run Code Online (Sandbox Code Playgroud)

对我来说这个功能应该如下,我没有看到克隆的需要.

  public function getStartDate ()
  {
    return $this->startDate;
  }
Run Code Online (Sandbox Code Playgroud)

Iva*_*jak 7

使用克隆的原因是PHP在处理对象时始终将对象作为引用返回,而不是作为副本.

这就是为什么在将对象传递给函数时,您不需要使用&(引用)指定它:

function doSomethingWithObject(MyObject $object) { // it is same as MyObject &object
   ...
}
Run Code Online (Sandbox Code Playgroud)

因此,为了获得对象副本,您必须使用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!
Run Code Online (Sandbox Code Playgroud)