PHP Pipeline,为什么对象被克隆了?

时间:2017-07-28 20:18:59

标签: 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 个答案:

答案 0 :(得分: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);