When is recommended to use read-only
properties — if the language allows me?
Are public read-only properties meant to replace getter
methods or at least the Magic Methods like what is available as __get() in PHP for example?
What is the use of a private read-only property?
4
read-only
properties are assigned only once – on the initialization of the instance.
It is different from getters
, since getters
allow the instance itself to change the value of the property. It is different from constants, since constants are assigned on the class declaration.
One use-case for read-only properties is to define immutable objects, another is in the definition of static read-only
for a singleton implementation.
Other use-cases may be in container properties (like lists and dictionaries), in which it is intended that their contents might change, but the collection itself stays with the instance for all its life-cycle. This way you can be sure that they are never nullified.
These are some use-cases of the top of my head, I’m sure that there are more…
3