Classes and objects provide named types with methods and properties that can be inspected or organized.
What Is Readonly Properties and Classes in PHP?
Readonly properties cannot be reassigned after initialization; readonly classes apply that rule to their declared instance properties.
Example 1: Understanding the Basic Behavior
<?php
final readonly class Money { public function __construct(public int $cents) {} }
echo (new Money(500))->cents;
Output:
500
Explanation: Readonly properties cannot be reassigned after initialization; readonly classes apply that rule to their declared instance properties.
Example 2: Testing Another Case
<?php
final class Order { public function __construct(public readonly string $id) {} }
echo (new Order('ORD-5'))->id;
Output:
ORD-5
Explanation: Readonly does not deeply freeze mutable objects referenced by properties; it protects the property binding.
Practical Example: Applying the Operation
<?php
final readonly class Address { public function __construct(public string $city, public string $country) {} }
$home = new Address('Rome', 'Italy');
echo $home->country;
Output:
Italy
Explanation: Visibility and inheritance affect which members exist and can be accessed directly.
Important Behavior and Edge Cases
- Readonly does not deeply freeze mutable objects referenced by properties; it protects the property binding.
- Visibility and inheritance affect which members exist and can be accessed directly.
Comparison With Related Approaches
| Approach | When to Use It |
|---|---|
Readonly Properties and Classes | Readonly properties cannot be reassigned after initialization; readonly classes apply that rule to their declared instance properties. |
Immutable value objects | Readonly prevents property reassignment; full immutability also requires guarding nested mutable objects and invariants. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Misinterpreting the documented behavior of Readonly Properties and Classes() for the supplied value. | Readonly does not deeply freeze mutable objects referenced by properties; it protects the property binding. |
| Choosing Immutable value objects without checking whether it provides the same result. | Readonly prevents property reassignment; full immutability also requires guarding nested mutable objects and invariants. |
Key Takeaways
- Readonly properties cannot be reassigned after initialization; readonly classes apply that rule to their declared instance properties.
- Readonly does not deeply freeze mutable objects referenced by properties; it protects the property binding.
- Visibility and inheritance affect which members exist and can be accessed directly.
The examples demonstrate where Readonly Properties and Classes fits within object-oriented php. Verify the relevant preconditions whenever you adapt the code to real data.