Re: Methods which auto-return the class instance

From: Date: Fri, 23 Dec 2022 13:29:07 +0000
Subject: Re: Methods which auto-return the class instance
References: 1 2 3  Groups: php.internals 
Request: Send a blank email to internals+get-119206@lists.php.net to get a copy of this message
> Le 23 déc. 2022 à 13:46, joke2k <joke2k@gmail.com> a écrit : > > On Fri, 23 Dec 2022, 09:33 Claude Pache, <claude.pache@gmail.com <•ƒÆgÀÓ¤ó$Gôð� > „¦mailto: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. > 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

« previous php.internals (#119206) next »