Constructor Property Promotion

PHP 8 introduces syntax sugar for reducing the amount of code that needs to be written for declaring object properties and initializing them in the constructor.

Here is an example of a class named Point that has three private properties $x, $y, and $z of type float that are set in the constructor:

final class Point
{
    public function __construct(
        private float $x,
        private float $y,
        private float $z,
    )
    {
    }
}

$p = new Point(1, 2, 3);

var_dump($p);

The code shown above is equivalent to the code shown below:

final class Point
{
    private float $x;
    private float $y;
    private float $z;

    public function __construct(float $x, float $y, float $z)
    {
        $this->x = $x;
        $this->y = $y;
        $this->z = $z;
    }
}

$p = new Point(1, 2, 3);

var_dump($p);

Executing both examples prints the same output:

object(Point)#1 (3) {
  ["x":"Point":private]=>
  float(1)
  ["y":"Point":private]=>
  float(2)
  ["z":"Point":private]=>
  float(3)
}