On 12/23/22, 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.
> But If you have declared `self` as return type into a non-static class
> method you have only two options to return:
>
> - the $this object
> - another instance of the same class or subclass
>
> ... in order to avoid a return type error.
>
> My proposal is to set the instruction `return $this;` as optional for
> non-static class methods with `self` declared as return type.
>
> Example:
> ```
> class Counter {
>
> public function __construct(private int $counter = 0) {}
>
> public function hit(): self { $this->counter++; }
> public function print(): self { echo $this->counter; }
>
> public function split(): self { return new self($this->counter); }
>
> }
>
> $main = (new Counter)->hit()->hit()->hit()->print()
> // 3
> $sub = $main->split()->hit()->print()
> // 4
> ```
>
> Thank you for reading my proposal,
> please let me know if you like it or if there are any issues with this.
>
> Regards,
>
> Daniele
>

As someone who used Scala for a number of years, I’d be very much
against this idea. Scala automatically returns the last line of any
function and we found it fairly difficult to maintain once the project
got fairly large and ended up switching to explicit returns. Mostly we
found it too easy to return the wrong thing.

In all fairness, I guess you technically don’t have to use it if you
don’t want to (you can use explicit returns), but IMHO, using this
would greatly affect readability. Every function you read that doesn’t
have a return, you’d have to check if the return type is self/static
and verify it is void.

-- 
Robert Landers
Software Engineer
Utrecht NL

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to