> On 25 Dec 2022, at 12:59, Ilija Tovilo <tovilo.il...@gmail.com> wrote: > > Hi Daniele > >> On Fri, Dec 23, 2022 at 1:09 AM joke2k <jok...@gmail.com> wrote: >> >> Hi folks, >> >> What do you think about having a method which returns the class instance >> `$this` by default only IF its return type is set as `self`? >> >> It is very common for fluent class methods to have a verbose `return >> $this;` ending in their body. > > Instead of adding special syntax to make writing fluent accessors > easier, I wonder if something akin to Dart's cascade operator would be > a better approach. > > https://dart.dev/guides/language/language-tour#cascade-notation > > $foo > ..setBar('bar') > ..setBaz('baz'); > > The syntax is just copied from Dart, there's probably a better fit for > PHP. .. would invoke a method call but discard the return value, > evaluating to the lhs of the method call instead. > > With an operator solution one can use fluent method calls on APIs that > aren't specifically designed for it when desired, accessors can become > leaner as return $this is no longer necessary, and it becomes obvious > at call-site that the chained methods are called on the same object. > > I'm not sure about syntax or the fact that Dart allows property > assignments in combination with .. as that makes the syntax ambiguous > (or whitespace sensitive), but that wouldn't be necessary for what > you're proposing. > > Example of the ambiguity: > > $foo > ..bar = $bar > ..baz() > // Could be parsed as > $foo..(bar = $bar)..baz() > $foo..bar = ($bar..baz()) > > An alternative might be a C# style syntax which would make property > assignments unambiguous. > > $foo { > setBar('bar'), > baz = 'baz', > } > > But this is also longer and less readable (to me at least). > > Anyway, just my unrefined thoughts. I would not support implicit > `return $this` for self or static. At the very least, the return type > should be $this (which is essentially a sub-type of static) but that > too doesn't seem like an elegant solution to me. > > Ilija > > -- > PHP Internals - PHP Runtime Development Mailing List > To unsubscribe, visit: https://www.php.net/unsub.php >
Out of all the ideas discussed here the only one that doesn’t seem like it lead to confusion or unexpected behaviour to me is the c# style statement which at the surface seems quite similar to the now-deprecated JS “with” statement. Cheers Stephen -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: https://www.php.net/unsub.php