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

[email protected] ("Rowan Tommins [IMSoP]")
Newsgroups php.internals
Message-ID <[email protected]>
On 1 July 2026 04:29:48 BST, Nick Sdot <[email protected]> wrote:
>
>```
>
>final readonly class Dog(
>    string $name,
>)extends Animal {
>    parent::__construct($name);
>}=> {
>    // class body }
>
>```
>
>The above:
>- does NOT have a parent constructor shortcut call -> `extends Animal`
>- DOES allow parent constructor call in primary constructor body
>- behaves exactly (!) as a conventional constructor; in fact syntax sugar
>
>```
>
>final readonly class Dog(
>    string $name,
>)extends Animal($name)// already IS the parent constructor call... {
>    // hence, here no parent constructor call allowed }=> {
>    // class body }
>
>```
>
>The above:
>- DOES have a parent constructor shortcut call -> `extends Animal($name)`
>- does NOT allow parent constructor call in primary constructor body
>- *no difference in parent constructor calling behaviour to what the RFC pr
ooposes now*
>
...

> So where is the complexity? 

So now we have to specify: 

- a brand new syntax for putting a code block outside the class body
- a parser rule to detect parent conductor calls (is ParentClassName::__construct also forbidden? What about DeeperAncestor::__construct?)
- the order of operations if there's a body and a shorthand parent call
- maybe other details of how the constructor body works which I haven't thought of


> What would justify not allowing the body that helps to address a real problem?

Many people see having more than one way to write the same thing as a cost, which needs to be outweighed by some benefit.

I'm on the fence whether primary constructors as they are in the current RFC are worthwhile; they're a tidy shorthand for a common case, but not saving that much over existing constructor promotion.

With your proposal to make them just a different way of writing any constructor, using a weird new syntax which puts code outside of the class body, I would be a definite "no".

That's just my opinion of the cost-benefit balance.



Rowan Tommins
[IMSoP]
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.