Hi Daniele and Claude,

pt., 23 gru 2022 o 10:33 Claude Pache <claude.pa...@gmail.com> napisał(a):

>
> > Le 23 déc. 2022 à 01:08, joke2k <jok...@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.
>

I like the idea of `$this` as a return type but also strongly believe that
the use of `return $this;` should be forbidden,
eventually for control flow use of `return;` might be justified.

Cheers,
Michał Marcin Brzuchalski

Reply via email to