Constructor Property Promotion is a new syntax in PHP 8 that allows class property declaration and constructor assignment right from the constructor.
In PHP (before version 8), when we created a class, we had to:
- Declare properties separately.
- Assign them inside the constructor.
This meant writing a lot of repeated code.
Old Way (Before PHP 8)
<?php
class Student {
public string $name;
public int $age;
public function __construct(string $name, int $age) {
$this->name = $name;
$this->age = $age;
}
}
$student = new Student("Amit", 21);
echo $student->name; // Output: Amit
?>
Here we are writing $name
and $age
two times:
- Once for property declaration
- Once again in constructor assignment
New Way in PHP 8 (Constructor Property Promotion)
In PHP 8, we can directly declare and assign class properties inside the constructor parameters.
<?php
class Student {
public function __construct(
public string $name,
public int $age
) {}
}
$student = new Student("Amit", 21);
echo $student->name; // Output: Amit
?>
Benefits:
- Less code, more readability
- Properties are automatically created and assigned
- No need to repeat yourself
Real-Life Example
<?php
class BankAccount {
public function __construct(
public string $holderName,
public string $accountNumber,
public float $balance
) {}
}
$account = new BankAccount("Rahul Sharma", "1234567890", 15000.50);
echo $account->holderName; // Rahul Sharma
echo $account->accountNumber; // 1234567890
echo $account->balance; // 15000.5
?>
Here, all details (holderName
, accountNumber
, balance
) are automatically created and assigned in one step.
Constructor Property Promotion in PHP 8 reduces boilerplate code and makes classes shorter and cleaner.