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

[email protected] ("Rowan Tommins [IMSoP]")
Newsgroups php.internals
Message-ID <[email protected]>
On 29 June 2026 11:52:45 BST, Rob Landers <[email protected]> wrote:
>
> FWIW, I was originally going to support them with something like:
>
>$arg = 'foo';
>$class = new class(public int $x = $arg) {}
>
>Which desugars to:
>
>$arg = 'foo';
>$class = new class($arg) {
>  public function __construct(public int $x) {}
>}


I actually have a draft RFC kicking around for this, but using a different syntax inspired by closures:

$arg = 'foo';
$class = new class() use (public int $arg) {}

This allows a very concise version for very simple cases: 

$class = new class() use ($arg) {}


I even had a working implementation, but paused it to work out if a constructor could be allowed as well. If the syntax allowed for a parent constructor call, though, that might be enough for most use cases.

Although it's not obvious, anonymous classes are actually compiled once, and then constructed multiple times, which means the syntax is doing quite a lot more than constructor promotion.

I agree that it should be left as future scope to pin down exactly how it should look and work.


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.