> Le 23 déc. 2022 à 13:46, joke2k <jok...@gmail.com> a écrit : > > On Fri, 23 Dec 2022, 09:33 Claude Pache, <claude.pa...@gmail.com > <mailto:claude.pa...@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. >
It is not about being less or more restricted, it is about being plainly ambiguous. ```php class Point { public function __construct( protected float $x , protected float $y ) { } public function withY(float $y): static { $newPoint = clone $this; $newPoint->y = $y; // oops, forgot “return $newPoint;” } } ``` With implicit behaviours (at least when there is more than one option), such sort of bugs become less apparent at runtime. Therefore, implicit behaviour ought to be avoided if possible. —Claude