Re: Methods which auto-return the class instance

From: Date: Fri, 23 Dec 2022 14:37:02 +0000
Subject: Re: Methods which auto-return the class instance
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-119207@lists.php.net to get a copy of this message
On 12/23/22, joke2k <joke2k@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

« previous php.internals (#119207) next »