Primary Constructors

From: Date: Wed, 17 Jun 2026 21:32:05 +0000
Subject: Primary Constructors
Groups: php.internals 
Request: Send a blank email to internals+get-131353@lists.php.net to get a copy of this message
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

« previous php.internals (#131353) next »