Re: Add $this return type

From: Date: Tue, 25 Jun 2024 07:44:34 +0000
Subject: Re: Add $this return type
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-123808@lists.php.net to get a copy of this message
On Tue, Jun 25, 2024 at 2:29 AM radar3301 <radar3301@gmail.com> wrote: > I'm looking for initial feedback on the following proposal. > > Often, we have the following (fluent interface) setter method: > > public function setName(?string $name): static > { > $this->name = $name; > > return $this; > } > > I propose to add "$this" as a return type, ie: > > public function setName(?string $name): $this > { > $this->name = $name; > // implicit return $this; > } > > public function setName(?string $name): $this > { > $this->name = $name; > // this would be an (compiler?) error > return $somethingOtherThanThis; > } > > public function setName(?string $name): $this > { > $this->name = $name; > $self = $this; > // this would not be an error > return $self; > } > > public function setName(?string $name): $this > { > $this->name = $name; > // technically useless, but not an error > return $this; > } > > public function setName(?string $name): $this > { > $this->name = $name; > if ('foobar' === $name) { > // not an error to return early > return; > } > // do some other stuff > > // any of the above legal examples > } > > It should be obvious, but functions outside of a class context would not > be able to use this syntax. > > BC: > There would be no BC breaks, as this syntax is currently invalid (Parse > error: syntax error, unexpected variable "$this"). > > Other Considerations: > With regards to reflection and inheritance, "$this" would be considered an > alias for "static". > > Regards, > radar3301 > I strongly agree that an alias for the "static" keyword is really necessary to improve the semantics of the language. The word "static" is used for many things: static methods, static classes and Late Static Bindings (that is the case that you are discussing). I think that in the case of Late Static Bindings (e.g. new static() or return type ..(): static), the word "static" does not give any clue about the meaning of that code. Thus, I like your proposal. The part that I do not like is the implicit return: it may confuse developers and static analysis tools. Is it possible to replace "$this" with "this"? Cleaner and coherent with "self". Regards, Luigi

« previous php.internals (#123808) next »