Re: Primary Constructors

From: Date: Wed, 17 Jun 2026 21:44:02 +0000
Subject: Re: Primary Constructors
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-131354@lists.php.net to get a copy of this message
On Wed, Jun 17, 2026, at 23:32, Rob Landers wrote: > Hello internals, > > I was reminded of my records RFC today, and one of the features of the RFC was "short > constructors" generally called "primary constructors" in C#/Kotlin. > > They would look like this: > > class Point(public int $x, int $id = 0) extends Base($id); > > Which is just sugar for this: > > class Point extends Base { > public function __construct(public int $x, int $id = 0) { > parent::__construct($id); > } > } > > or this: > > class Point extends Base { > public int $x; > public function __construct(int $x, int $id = 0) { > $this->x = $x; > parent::__construct($id); > } > } > > A class with a primary constructor *may not* have a defined > __construct function. Any special initialization must be done with > hooks: > > class Temperature( > public float $celsius { > set { > if ($value < -273.15) { > throw new ValueError('below absolute zero'); > } > $this->celsius = $value; > } > } > ) {} > > new Temperature(20.0); // ok > new Temperature(-300.0); // ValueError: below absolute zero > > I'm sending this email to the list to gather additional feedback before pursuing a formal > RFC proposal. > > — Rob I just realized that my examples did not demonstrate the classes with a body, but they may also have a body! — Rob

« previous php.internals (#131354) next »