Classes and objects provide named types with methods and properties that can be inspected or organized.
What Is Readonly Properties vs Readonly 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 vs Readonly Classes | Readonly properties cannot be reassigned after initialization; readonly classes apply that rule to their declared instance properties. |
Readonly classes | A readonly property protects one field, while a readonly class automatically marks its declared instance properties readonly. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Misinterpreting the documented behavior of Readonly Properties vs Readonly Classes() for the supplied value. | Readonly does not deeply freeze mutable objects referenced by properties; it protects the property binding. |
| Choosing Readonly classes without checking whether it provides the same result. | A readonly property protects one field, while a readonly class automatically marks its declared instance properties readonly. |
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 vs Readonly Classes fits within object-oriented php. Verify the relevant preconditions whenever you adapt the code to real data.