[英]PHP Pipeline, why is the object getting cloned?
I was looking at some php code and stumbled on a pipeline script. 我在看一些php代码,偶然发现了管道脚本。 In the method to add something to the pipeline:
在向管道添加内容的方法中:
public function pipe(callable $stage)
{
$pipeline = clone $this;
$pipeline->stages[] = $stage;
return $pipeline;
}
The object is getting cloned, and returned. 该对象将被克隆并返回。 Could someone explain me the advantages of this approach, wouldn't the following code return the same results?
有人可以向我解释这种方法的优势,下面的代码不会返回相同的结果吗?
public function pipe(callable $stage)
{
$this->stages[] = $stage;
return $this;
}
No, it won't return the same. 不,它不会返回相同的值。
Clone
creates a copy of the object, which is sometimes the desired behaviour. 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.