Methods which auto-return the class instance
| From: | joke2k | Date: | Fri, 23 Dec 2022 00:08:32 +0000 |
| Subject: | Methods which auto-return the class instance | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-119200@lists.php.net to get a copy of this message | ||
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