Re: Methods which auto-return the class instance

From: Date: Fri, 23 Dec 2022 09:33:34 +0000
Subject: Re: Methods which auto-return the class instance
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-119202@lists.php.net to get a copy of this message
> Le 23 déc. 2022 à 01:08, joke2k <joke2k@gmail.com> a écrit : > > 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. It is still two options, and it is not clear in general which one to pick. You could also say that, if you have object as return type, there are two options to avoid a return type error: either return the $this object, or return another object. > > My proposal is to set the instruction return $this; as optional > for > non-static class methods with self declared as return type. I’d rather have a syntax saying explicitly that you want to return $this, rather than letting the interpreter guess what you meant. The obvious one is: ```php public function hit(): $this { $this->counter++; } ``` Here, there is only one possible return value, and therefore the return instruction might be reasonably omitted. The real question is: Is it worth to add special cases for some specific return values? —Claude

« previous php.internals (#119202) next »