Declared properties avoid deprecated dynamic-property creation on ordinary classes since PHP 8.2.
What It Does
Declared properties avoid deprecated dynamic-property creation on ordinary classes since PHP 8.2. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Declare properties explicitly instead of assigning undeclared fields.
<?php
class CartLine { public int $quantity = 0; }
$line = new CartLine(); $line->quantity = 3; echo $line->quantity;
Example 2: Another Case
Constructor promotion declares fields for you.
<?php
final class CustomerProfile { public function __construct(public string $name, public ?string $nickname = null) {} }
echo (new CustomerProfile('Maya'))->name;
Practical Example: Putting It to Use
Store external object metadata in WeakMap when changing the class is impossible.
<?php
$metadata = new WeakMap();
$object = new stdClass(); $metadata[$object] = ['request_id' => 'r5'];
echo $metadata[$object]['request_id'];
Important Behavior and Edge Cases
stdClass and some magic-property patterns are exceptions, not a general migration strategy.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Replacing Dynamic Properties with Declared Properties | Declared properties avoid deprecated dynamic-property creation on ordinary classes since PHP 8.2. |
| Related approach | WeakMap can store external metadata without editing object classes. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Replacing Dynamic Properties with Declared Properties | stdClass and some magic-property patterns are exceptions, not a general migration strategy. |
| Assuming a related mechanism has the same behavior | WeakMap can store external metadata without editing object classes. |
Key Takeaways
- Declared properties avoid deprecated dynamic-property creation on ordinary classes since PHP 8.2.
- stdClass and some magic-property patterns are exceptions, not a general migration strategy.
- WeakMap can store external metadata without editing object classes.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.