PHP › PHP 8 Features (Attributes, Enums, Match, Nullsafe Operator)
How do constructor property promotion, introduced in PHP 8, reduce boilerplate code when defining a class with several properties initialized directly through its constructor?
IntermediateAnswer
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.