Re: [PHP-DEV] [RFC] Primary Constructors

[email protected] (Nick Sdot)
Newsgroups php.internals
Message-ID <[email protected]>
On 29.06.26 08:17, Rob Landers wrote:
> Hello internals,
>
> I'd like to put forward Primary Constructors 
> <https://wiki.php.net/rfc/primary-constructors> for comment.
>
> An implementation PR will be opened later today (UTC), and the RFC 
> updated with this discussion thread.
>
> — Rob


Hey Rob,

thanks again for the work you did put into this!

Unfortunately you are not allowing bodies for primary constructor. This 
means there will be no way to work around the "`readonly` classes don't 
allow property hooks" problematic; except using conventional 
constructors (`private(set)` is not the same; hence my previous 
"readonly hooks" RFC).

If "use conventional constructors, if you need `readonly` classes" 
stands, then the same can be argued for everything else in the RFC.

Why would we introduce a whole new syntax, but then only make it work 
for limited use-cases such as "trivial validation or normalization"?

Your example:

```

class Money(
     public readonly int$amount,
     public readonly string$currency = 'USD',
) {}

class Money{
     public function __construct(
         public readonly int$amount,
         public readonly string$currency = 'USD',
     ) {}
}

```

Pro:
- two lines less
- construction at top of class (love it!)

Con:
- primary constructor body not supported
- new syntax with gotchas to keep in mind
- for readonly classes it adds two property `readonly` in exchange to 
writing two lines less
- requires refactoring to conventional constructor as soon as it gets 
"non-trivial" (I'd argue a lot of things that do not work are actually 
still trivial).

Given the limitations, is this alone adding enough value? What is the 
actual gain?

Adding a new syntax to the language but then lock it down as proposed 
here does not feel right.
As is, I feel the proposal is too thin, it would unfortunately be yet 
another feature that feels mid, incomplete, and introduces new gotchas.
Sorry, IMO, not worth it.

If we would say we want new and neat syntax sugar to write constructors 
at the top of the class, I am all for it!
But then they would need to work like actual constructors (otherwise 
it's not just sugar), without accepting yet another set of limitations 
and weirdness's in a different place.

What I roughly have in mind:

```
readonly class Point(public int $x, int $id = 0) extends Base($id) 
implements Foo {
    // normal constructor body behaviour
} => {
   // class body
}
```

--

Cheers
Nick
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.