> 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.

The real question is: Is it worth to add special cases for some specific return 
values?

—Claude

Reply via email to