How do constructor property promotion, introduced in PHP 8, reduce boilerplate code when defining a class with several properties initialized directly through its constructor?
Short answer
Constructor property promotion lets you declare and initialize a class property directly within the constructor's parameter list, simply by adding a visibility modifier before the parameter, eliminating the previously required boilerplate of separately declaring each property…
Advertisement
AModel answer
Constructor property promotion lets you declare and initialize a class property directly within the constructor's parameter list, simply by adding a visibility modifier before the parameter, eliminating the previously required boilerplate of separately declaring each property, adding a matching constructor parameter, and manually assigning that parameter's value to the corresponding property inside the constructor body.
class Point {
public function __construct(
public readonly float $x,
public readonly float $y
) {}
}Real-world example
A developer refactors a data class that previously required a dozen lines of repetitive property declarations and constructor assignment code down to just a few concise lines using constructor property promotion, significantly improving readability.
Likely follow-ups
- Can constructor property promotion be combined with the readonly modifier?
- Is there any functional difference between a promoted property and a traditionally declared one?
Related topics