Constructor promotion is a shortcut to declare and assign properties in one step. Add public or private before a constructor parameter and PHP does the rest automatically. It removes repetitive property boilerplate.
Constructor Property Promotion (PHP 8)
// Before — repetitive
class Point {
public float $x;
public float $y;
public float $z;
public function __construct(float $x, float $y, float $z) {
$this->x = $x;
$this->y = $y;
$this->z = $z;
}
}
// After — constructor promotion
class Point {
public function __construct(
public float $x,
public float $y,
public float $z = 0.0,
) {}
}
$p = new Point(1.0, 2.0);
echo $p->x; // 1.0
// Combine with readonly
class Config {
public function __construct(
public readonly string $host,
public readonly int $port = 3306,
) {}
}