Classes and objects provide named types with methods and properties that can be inspected or organized.
What Is readonly vs Immutable Objects 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 vs Immutable Objects | Readonly properties cannot be reassigned after initialization; readonly classes apply that rule to their declared instance properties. |
Immutable objects | Readonly prevents reassignment of bindings; domain immutability must also avoid exposing mutable nested state. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Misinterpreting the documented behavior of readonly vs Immutable Objects() for the supplied value. | Readonly does not deeply freeze mutable objects referenced by properties; it protects the property binding. |
| Choosing Immutable objects without checking whether it provides the same result. | Readonly prevents reassignment of bindings; domain immutability must also avoid exposing mutable nested state. |
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 vs Immutable Objects fits within object-oriented php. Verify the relevant preconditions whenever you adapt the code to real data.