Re: [RFC] Primary Constructors
| From: | Nick Sdot | Date: | Wed, 01 Jul 2026 11:25:53 +0000 |
| Subject: | Re: [RFC] Primary Constructors | ||
| References: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-131653@lists.php.net to get a copy of this message | ||
Hey Rowan,
On 01.07.26 18:43, Rowan Tommins [IMSoP] wrote:
On 1 July 2026 09:51:00 BST, Nick Sdot<php@nicksdot.dev> wrote:Not sure how else I could explain it. What's not clear? Trying... The limitation are property hooks inJust imagine you have to refactor an existing class with a primary constructor.I don't understand this paragraph at all. The proposed syntax doesn't change anything about how readonly works, as far as I know. Any "primary constructor body" or "init block", whatever syntax it had, would have exactly the same abilities and limitations regarding readonly properties as a normal constructor. It would just be a different way of spelling it. Rowan Tommins [IMSoP]readonlywould prevent what you want to do and must be removed. This would require you to check and refactor the whole class, instead of just adding a body. It doesn't make sense.
readonly classes. By having the primary constructor body with "exactly the same abilities and limitations regarding readonly properties as a normal constructor" you *can* assign the property in question in the primary constructor body. If there is no body, you cannot work around it. Unless, of course, you don't use primary constructors. Which brings me back to "new, great feature unusable in endless situations" -- which should not be our aim IMO.
You cannot do the below with a hook. Having the primary constructor body solves it:
final readonly class Foo(Collection|array $value) implementsBar {
$this->items = $value instanceof Collection ? $value : new Collection($value);
}=> {
// class body private Collection $items
}
I really like the general idea of this RFC, and I would like to have it. But without bodies it's broken in too many situations.
--
Cheers
Nick