PHP

PHP 8.0 Constructor Property Promotion

Constructor Property Promotion

Hello Everyone, Welcome to my blog post. Today, I would like to discuss about the constructor property promotion. 

What is Constructor Property Promotion

PHP has recently launched its new version i.e. PHP 8 and it consists of many new features. Constructor property promotion is one of the new features introduced in PHP 8. In previous versions of PHP(~7.*), we used to define our variables as class property and assign its value in the constructor. Please check out the following example for reference:

class Point {
  public float $x;
  public float $y;
  public float $z;

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

In the above example, we can see the $x, $y & $z is defined as class property and we have assigned a value in the constructor, and it requires a lot of boilerplate because all properties need to be repeated at least four times.

The properties are repeated 

1) in the property declaration.

2) the constructor parameters.

3) two times in the property assignment. Additionally, the property type is repeated twice.

To avoid this repetitive assignment PHP 8 came up with a new solution in the new version. Please check out the following example for reference.

class Point {
  public function __construct(
    public float $x = 0.0,
    public float $y = 0.0,
    public float $z = 0.0,
  ) {}
}

Here, we can use the shorthand syntax which allows combining the definition of properties and the constructor. In the constructor, we are assigning variable values with access specifiers. 

When we prefix variable with one of the access specifiers like private, public, and protected it is considered as “promoted”. For every promoted parameter, a property with the same name will be added for example.

public float $x = 0.0

A variable is assigned with $x, this shorthand syntax is inherited from the sister site of PHP Hack

Please let me know your thought about this blog in the comment section below. Or, you can write me an email on my email id i.e. admin@asolutions.co.in. Till next time happy coding :). 

[post-views]

Tagged , , ,

3 thoughts on “PHP 8.0 Constructor Property Promotion

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.