PHP – Constructor Property Promotion

In PHP 8, the constructor property promotion is a feature that was added that reduces the amount of code that needs to be typed for working with constructor properties. This feature can be beneficial by reducing the amount of typing that is needed to be done.

Constructor property promotion works by removing the declaration of a property that is assigned in the constructor and removing that assignment in the constructor by adding the visibility keyword to the constructor parameter.

Example Without Constructor Property Promotion

The below code shows an example of using constructor properties without using property promotion:

class Person 
{
    public string $firstName;
    public string $lastName;
    
    public function __construct(string $firstName, string $lastName)
    {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
    }
}

$p1 = new Person("Jessie", "Edmisten");
print_r($p1);  // Person Object ( [firstName] => Jessie [lastName] => Edmisten )

The above code does the following:

  1. Declares the class properties using the visibility keyword, data type, and then the variable name.
  2. When the class is instantiated the variables are passed into the constructor as parameters.
  3. The values of the passed in variables are assigned to the class properties.
  4. The output of the print_r command displays the values that have been assigned to the class properties of this instance of the Person object.

Example Using Constructor Property Promotion

The below code shows an example of using contructor property promotion to reduce the amount of code:

class Person 
{
    public function __construct(public string $firstName, public string $lastName) {}
}

$p1 = new Person("Jessie", "Edmisten");
print_r($p1);  // Person Object ( [firstName] => Jessie [lastName] => Edmisten )

In the above code, the parameters of the constructor are updated to have the visibility keyword (public) of each parameter. By adding the visibility keyword in front of the parameter the PHP parser now knows to declare the property and assign the property to the value passed in to the parameter. The output of the print_r command will display the specific strings that are now assigned to the class properties.

Because the body of this constructor was only used to assign values to the class properties, the body of the constructor can now be reduced to {}.

This example shows how using constructor property promotion can significantly reduce the amount of code that needs to be typed. This can also potentially make the code more readable.

An important point to know is that this can only be done for constructors.


References:
https://www.php.net/manual/en/language.oop5.decon.php#language.oop5.decon.constructor.promotion
https://laracasts.com/series/php8-crash-course/episodes/4