
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
Constructor Property Promotion in PHP 8
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
- Related Articles
- JavaScript Boolean constructor Property
- JavaScript Date constructor Property
- Pass arguments from array in PHP to constructor
- Can we define constant in class constructor PHP?
- Difference between constructor and ngOnInit in Angular 8
- How to call parent constructor in child class in PHP?
- Attributes in PHP 8
- C# Numeric Promotion
- Add a property to a JavaScript object constructor?
- Number comparisons in PHP 8
- Named Arguments in PHP 8
- Union Type in PHP 8
- Match Expression in PHP 8
- Nullsafe Operator in PHP 8
- fdiv() function in PHP 8

Advertisements