0

I was looking at some php code and stumbled on a pipeline script. 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;
}
  • 1
    I guess the best explanation (and probably with examples) can be provided by the author of the library. – axiac Jul 28 '17 at 20:36
  • @axiac Completely agree with you! But 9 out of 10 when people use in php keyword `clone` - they wanna solve one particular problem... – cn007b Jul 29 '17 at 06:46

1 Answers1

0

No, it won't return the same. Clone creates a copy of the object, which is sometimes the desired behaviour.

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);
Peter van der Wal
  • 11,141
  • 2
  • 21
  • 29
  • 1
    clone() creates a copy of an object using the __clone() method and could still have sides effects if the cloned object has attributes that are reference object. – Sebastien Jul 28 '17 at 20:33