What are 'Readonly Classes' in PHP 8.2, and why can't they contain non-readonly properties?
Last updated
A
readonly classmakes every typed instance propertyreadonly, producing immutable objects initialized once (ideal for value objects and DTOs).Non-readonly properties are forbidden because they would break the immutability guarantee. Untyped and static properties are disallowed for the same reason.
Immutability is shallow: an object held in a property can still have its internals mutated.
- https://www.php.net/manual/en/language.oop5.basic.php
- https://wiki.php.net/rfc/readonly_classes
- https://stitcher.io/blog/readonly-classes-in-php-82
- https://externals.io/message/116472
- https://doganoo.medium.com/readonly-classes-in-php-a-useful-addition-to-readonly-properties-4457b27a9f16
- https://php.watch/versions/8.2/readonly-classes
- https://dogan-ucar.de/en/do-readonly-properties-replace-getters-in-php/
- https://stitcher.io/blog/new-in-php-82