Re: Proposal for php7 class method return
| From: | Jesse Schalken | Date: | Sun, 10 Jul 2016 12:31:42 +0000 |
| Subject: | Re: Proposal for php7 class method return | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-94460@lists.php.net to get a copy of this message | ||
On Sun, Jul 10, 2016 at 8:34 PM, Rasmus Schultz <rasmus@mindplay.dk> wrote:
>
> What you're really trying to accomplish is something like the ".."
> operator found in some other languages - this is known as the "cascade
> operator" in Dart, for example:
>
>
>
> http://news.dartlang.org/2012/02/method-cascades-in-dart-posted-by-gilad.html
>
>
While I was writing about an operator to set object properties in-line
here: http://news.php.net/php.internals/93662
, I considered it would be
easy to add method calls to the same syntax:
return Blah::create(5) {
prop1 = 'hello',
prop2 = a_func(),
setThing(9),
setOtherThing(1),
};
which is in principle just an alternative syntax to as the cascade operator
in Dart.
I agree entirely that method chaining is just a verbose workaround for the
lack of such a language feature. I've found a few problems with method
chaining which this would resolve:
1. The verbosity of adding "return $this;" to all your mutator methods
(Daniel Ciochiu's issue).
2. You can't return a value from a mutator method while also supporting
method chaining. In theory mutator methods shouldn't need a return value
(command-query separation) but in many cases they do, such as a setter
which returns the previous value, a pop() method on a stack, or a
delete($where) method returning the number of deleted records.
3. It is often unclear whether a method being chained is returning the
same object it was called on, a copy of the object, or an instance of a
different class altogether. You can work around this with careful method
naming and documentation ("with.." for new instance, "set.." for same
instance etc), but language-level support eliminates this issue entirely.
You could really solve a whole range of problems with such a feature.