PHP Reference ยท Functions and Classes
PHP constructor property promotion
Reference for PHP constructor property promotion (PHP 8.0+): declare and assign properties in the constructor signature, with readonly, defaults and rules.
Constructor property promotion lets you declare a property and assign it in one place: put a visibility modifier in front of a constructor parameter, and PHP creates a property with that name and type and copies the argument into it. It was added in PHP 8.0.
It replaces the three-step pattern of declaring a property, listing a parameter and writing $this->x = $x;. Promoted and ordinary parameters can be mixed in the same constructor.
class Point { public function __construct( public int $x = 0, public int $y = 0, ) { } }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
public function __construct( [visibility] [readonly] [type] $name [= default], ... ) { /* optional body, runs after the properties are assigned */ }
A parameter is promoted when it has a visibility modifier (public, protected, private), readonly, or both. PHP 8.4 also accepts asymmetric visibility such as public private(set), and property hooks in promoted parameters.
Rules:
- Only constructors can promote parameters.
- Promoted properties are assigned before the constructor body runs, so the body can use
$this->name. - A promoted property cannot also be declared in the class body.
abstractconstructors and constructors in interfaces cannot promote.- A promoted parameter cannot use the type
callable, because properties cannot. - A promoted variadic parameter is not allowed.
- The old implicit-nullable form
string $x = nullis deprecated in PHP 8.4; write?string $x = null.
Usage notes
- Parameter default values apply to the property when the argument is omitted.
- The property is typed exactly like the parameter. A union type parameter gives a union type property.
- Combine with
readonlyto build small immutable value objects in a few lines. - Attributes placed on a promoted parameter apply to both the parameter and the property.
- Doc comments on promoted parameters are kept as property doc comments.
- Inheritance: a child constructor that promotes its own parameters must call
parent::__construct()itself if the parent needs setup. - Reflection reports promoted properties like any others;
ReflectionProperty::isPromoted()tells you which ones came from the constructor. - Not for everything. If a property needs a derived initial value, declare it normally and compute it in the body.