2017-07-28 65 views
0

我正在看一些php代码,并偶然发现了一个管道脚本。在向管道中添加内容的方法中:PHP管道,为什么对象被克隆?

public function pipe(callable $stage) 
{ 
    $pipeline = clone $this; 
    $pipeline->stages[] = $stage; 
    return $pipeline; 
} 

该对象正在克隆并返回。 有人可以解释我这种方法的优点, 会不会在下面的代码返回相同的结果?

public function pipe(callable $stage) 
{  
    $this->stages[] = $stage; 
    return $this; 
} 
+1

我想最好的解释(可能与例子)可以由图书馆的作者提供。 – axiac

+0

@axiac完全同意你的看法!但是,当人们在php关键字clone中使用9时 - 他们想要解决一个特定的问题... –

回答

0

不,它不会返回相同的。 Clone创建对象的副本,这有时是所需的行为。

class WithoutClone { 
    public $var = 5; 

    public function pipe(callable $stage) 
    {  
     $this->stages[] = $stage; 
     return $this; 
    } 
} 

$obj = new WithoutClone(); 
$pipe = $obj->pipe(...); 
$obj->var = 10; 
echo $pipe->var; // Will echo 10, since $pipe and $obj are the same object 
       // (just another variable-name, but referencing to the same instance); 

// ---- 

class Withlone { 
    public $var = 5; 

    public function pipe(callable $stage) 
    {  
     $pipeline = clone $this; 
     $pipeline->stages[] = $stage; 
     return $pipeline; 
    } 
} 

$obj = new WithClone(); 
$pipe = $obj->pipe(...); 
$obj->var = 10; 
echo $pipe->var; // Will echo 5, since pipe is a clone (different object); 
+1

clone()使用__clone()方法创建一个对象的副本,并且如果克隆的对象仍然有副作用具有参考对象的属性。 – Sebastien