Re: Proposal for php7 class method return
| From: | Jesse Schalken | Date: | Mon, 11 Jul 2016 19:51:15 +0000 |
| Subject: | Re: Proposal for php7 class method return | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-94475@lists.php.net to get a copy of this message | ||
On Mon, Jul 11, 2016 at 10:18 PM, Marco Pivetta <ocramius@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,
});