On Mon, Jul 11, 2016 at 10:18 PM, Marco Pivetta <ocram...@gmail.com> wrote:

> Hi Jesse,
>
> `return $this;` is a fairly common anti-pattern. It can be useful in few
> edge-cases, like immutable APIs (CoW) and DSL builders, but it's usually a
> bad idea. I ranted extensively about this at
> https://ocramius.github.io/blog/fluent-interfaces-are-evil/
>

I agree, but nonetheless at the cost of the problems both you (in your blog
post) and I have mentioned, "return $this;" does save the verbosity of
repeating a variable name, and often saves a variable altogether:

$blah = new Blah();
$blah->setFoo(1);
$blah->setBaz(2);
$this->setBlah($blah);


becomes

$this->setBlah((new Blah())
    ->setFoo(1)
    ->setBaz(2)
);


Some cascade operator or inline group method call/property set achieves the
same thing, but without all the problems of "return $this;":

$this->setBlah((new Blah())
    ->>setFoo(1)
    ->>setBaz(2)
);


$this->setBlah(new Blah() {
    setFoo(1),
    setBaz(2),
});


$this->setBlah(new Blah() {
    foo = 1,
    baz = 2,
});

Reply via email to