Re: Methods which auto-return the class instance
| From: | joke2k | Date: | Fri, 23 Dec 2022 12:46:25 +0000 |
| Subject: | Re: Methods which auto-return the class instance | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-119205@lists.php.net to get a copy of this message | ||
Thanks for the feedback!
On Fri, 23 Dec 2022, 09:33 Claude Pache, <claude.pache@gmail.com> wrote:
> 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.
>
Yes but declaring self is more strict than object.
And talking about the word itself... Declaring to return (your-)self but
you could return someone-else of the same type as you.
But it is ok, it refers to the class name not the instance. just semantic.
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.
>
Return $this is a valid alternative indeed. It is an explicit subclass of
returning self which has a default return object, itself.