PHP 8: Constructor property promotion

php-8-banner

It’s typical for constructor arguments to be allocated to a property in the constructor but never used. PHP 8 added constructor promotion as a convenient shorthand for such scenario.

Below is a typical constructor pre PHP 8:

1
2
3
4
5
6
7
8
9
10
11
class Order
{
    public int $id;

    public string $description;

    public function __construct(string $id, string $description) {
        $this->id = $id;
        $this->description = $description;
    }
}

It seems just repetitive work with no real benefits. Thankfully, starting PHP 8.0, when a visibility modifier is included in a constructor argument, PHP treats it as both an object property and a constructor argument, and assigns the argument value to the property.

So you can now write this in PHP 8:

1
2
3
4
5
6
class Order
{
    public function __construct(public int $id, public string $description)
    {
    }
}

With much cleaner and shorter syntax, property promotion allows you to integrate class fields, constructor definitions, and variable assignments – all into a single syntax.

The Promoted properties can have default value

1
2
3
4
public function __construct(
    public int $id = 1,
    public string $description = 'foo'
) {}

It’s OK to combine promoted and normal properties

1
2
3
4
5
6
7
8
9
10
11
class Order
{
    public  $description;

    public function __construct(
        public int $id,
        string $description
    ) {
        $this->description = $description;
    }
}

It’s important to note that you can’t have the same name for a class property and a promoted property.

Do not use ‘var’

Finally, when declaring class variables for constructor property promotion, do not use ‘var’. Only the terms “public,” “protected,” and “private” are permitted.

So the following is not a valid constructor property promotion:

1
public function __construct(var string $foo) {}

That’s all there is to it. The constructor property promotion makes your code cleaner, shorter, and more awesome! Learn to start using it today.

Recommended read:
https://www.php.net/manual/en/language.oop5.decon.php#language.oop5.decon.constructor.promotion