Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Constructor Property Promotion in PHP 8
Constructor Property Promotion is a powerful PHP 8 feature that significantly reduces boilerplate code when creating simple classes. It allows you to combine property declaration, constructor definition, and variable assignment into a single, clean syntax.
Traditional PHP 7 Approach
Before PHP 8, creating a class with properties required separate property declarations and manual assignments ?
<?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 = $a;
$this->b = $b;
$this->c = $c;
}
}
$account = new Account(10.90, 20.0, 30.80);
echo $account->a . " " . $account->b . " " . $account->c;
?>
10.9 20 30.8
PHP 8 Constructor Property Promotion
With constructor property promotion, you can declare properties directly in the constructor parameters ?
<?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);
echo $account->a . " " . $account->b . " " . $account->c;
?>
10.9 20 30.8
Employee Example
Here's another example demonstrating constructor property promotion with different data types ?
<?php
class Employee {
public function __construct(
public int $id,
public string $name
) {}
}
$employee = new Employee(11, 'Alex');
echo "ID: " . $employee->id . ", Name: " . $employee->name;
?>
ID: 11, Name: Alex
Key Benefits
Constructor Property Promotion offers several advantages:
- Reduced Code − Eliminates repetitive property declarations and assignments
- Improved Readability − Properties are visible directly in the constructor
- Type Safety − Maintains full type declaration support
- Default Values − Supports default parameter values like traditional constructors
Conclusion
Constructor Property Promotion in PHP 8 streamlines class creation by combining property declaration and initialization in one syntax. This feature reduces boilerplate code while maintaining type safety and readability, making your PHP code more concise and maintainable.
