Re: Optional constructor body
| From: | Ayesh Karunaratne | Date: | Thu, 18 Jul 2024 09:40:05 +0000 |
| Subject: | Re: Optional constructor body | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-124468@lists.php.net to get a copy of this message | ||
>
> Hello internals.
>
> I am looking into making the constructor body optional in classes, essentially allowing you to
> write
>
> ```
> class User {
> public function __construct(
> private string $name,
> )
> }
> ```
>
> Currently to make this code valid, it would have to be written the following way
>
> ```
> class User {
> public function __construct(
> public string $name,
> ) {}
> }
> ```
>
> With the introduction or constructor property promotion in 8.0, we often see classes where the
> constructor has an empty body, and my guess would be that this will only increase with the
> introduction of property access hooks in 8.4 which is allowed to be defined in the constructor also.
>
> This change would only be a cosmetic change and simplify the userland code by removing two
> redundant characters.
>
>
>
> This would be my first RFC and I am willing to try and implement it myself.
>
>
> Best regards
> Oliver Nybroe (he/him)
Hi Oliver,
Some links to previous discussions when this was brought up in the
mailing list before:
- https://externals.io/message/114324
- https://externals.io/message/111590
I followed those discussions closely back then, and I suppose the
general sentiment (to which I also agree) was that this is more of a
code style consideration rather than a technical one. Although it's a
cosmetic change, the fact that it will cause BC issues on older PHP
versions was a significant concern; now more so after we had
Constructor Properties for 4 years.
I think you can gather more pre-RFC opinions from this mailing thread,
especially now that this is brought up after a while since Constructor
Properties were introduced.
If you do with to go with an RFC, I'd like to see if your proposal
addresses whether this syntax should implicitly call
parent::__construct(), and if a semi colon is expected or not
(public function __construct(public int $foo); vs `public function
__construct(public int $foo)`).
Ayesh.