In PHP 8, Constructor Property Promotion is added. It helps to reduce a lot of boilerplate code while constructing simple objects. This feature allows us to combine class fields, constructor definition, and variable assignments, all in one syntax, into the constructor parameter list.
We can say that instead of specifying class properties and a constructor, we can combine all of them using constructor property promotion.
Example 1: PHP 7 Code
<?php class Account { public float $a; public float $b; public float $c; public function __construct( float $a = 0.0, float $b = 0.0, float $c = 0.0, ) { $this->a = $x; $this->b = $y; $this->c = $z; } } ?>
Example 2: PHP 8 code
We can re-write the above PHP 7 code in PHP 8 as follows −
<?php class Account { public function __construct( public float $a = 0.0, public float $b = 0.0, public float $c = 0.0, ) {} } $Account =new Account (10.90,20.0,30.80); print_r($Account->a); print_r($Account->a); print_r($Account->a); ?>
Output
10.9 20 30.8
In the above code, we combined property definition and population inline in the constructor signature. This code will remove repetition.
Example 3: PHP 8 Code for Constructor Property Promotion
<?php class Employee { public function __construct( public int $id, public string $name, ) {} } $employee = new Employee(11, 'Alex'); print_r($employee->id); print_r($employee->name); ?>
Output
11 Alex