Constructor property promotion is a syntactic shorthand introduced in PHP 8.0 that merges class property declaration, constructor parameter definition, and property assignment into a single construct. By prefixing a constructor parameter with a visibility modifier (Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
public, protected, or private), the PHP engine automatically declares a corresponding class property and assigns the passed argument to it during object instantiation.
Syntax Mechanics
To trigger property promotion, the parameter within the__construct method signature must include a visibility modifier.
Traditional Syntax:
Technical Rules and Constraints
1. Allowed Contexts Property promotion is strictly limited to the__construct method. It cannot be used in standard methods, static methods, abstract constructors, or interface declarations.
2. Mixing Promoted and Non-Promoted Parameters
You can mix promoted properties with standard constructor parameters. Standard parameters lack a visibility modifier and will not generate a class property.
callable: Promoted properties cannot be typed ascallable. Becausecallableis not a valid property type in PHP (due to context-dependent scope issues), the engine rejects it during promotion.- Variadic Parameters: Variadic parameters (e.g.,
...$args) cannot be promoted. - Untyped Parameters: Omitting the type leaves the property completely untyped. This is distinct from an explicit
mixedtype. For example, in Reflection, an untyped property returnsnullforgetType(), whereas an explicitmixedtype returns aReflectionNamedType.
readonly modifier can be used to promote a property. It must strictly be accompanied by a visibility modifier (public, protected, or private). Furthermore, due to PHP’s language constraints on readonly properties, promoted readonly properties must be explicitly typed. Attempting to promote an untyped readonly property (e.g., public readonly $id) will result in a fatal error.
Attribute Resolution
When applying PHP Attributes to a promoted property, the engine blindly applies the attribute to both the generated class property and the constructor parameter. PHP does not validate attribute targets during the initial parsing phase. If an attribute is strictly restricted to a specific target (e.g.,Attribute::TARGET_PROPERTY), it will still be attached to the constructor parameter. Consequently, invoking ReflectionAttribute::newInstance() on that parameter will throw a fatal error (Error: Attribute "..." cannot target parameter).
Master PHP with Deep Grasping Methodology!Learn More





