In using PHP's DOM classes (DOMNode, DOMEElement, etc) I have noticed that they possess truly readonly properties. For example, I can read the $nodeName property of a DOMNode, but I cannot write to it (if I do PHP throws a fatal error).
How can I create readonly properties of my own in PHP?
Here is a way to render all property of your class read_only from outside, inherited class have write access ;-).
tested in php7
For those looking for a way of exposing your private/protected properties for serialization, if you choose to use a getter method to make them readonly, here is a way of doing this (@Matt: for json as an example):
You can do it like this:
Only use this when you really need it - it is slower than normal property access. For PHP, it's best to adopt a policy of only using setter methods to change a property from the outside.
But private properties exposed only using __get() aren't visible to functions that enumerate an object's members - json_encode() for example.
I regularly pass PHP objects to Javascript using json_encode() as it seems to be a good way to pass complex structures with lots of data populated from a database. I have to use public properties in these objects so that this data is populated through to the Javascript that uses it, but this means that those properties have to be public (and therefore run the risk that another programmer not on the same wavelength (or probably myself after a bad night) might modify them directly). If I make them private and use __get() and __set(), then json_encode() doesn't see them.
Wouldn't it be nice to have a "readonly" accessibility keyword?
I see you have already got your answer but for the ones who still are looking:
Just declare all "readonly" variables as private or protected and use the magic method __get() like this:
As you can see I have also protected the $this->instance variable as this method will allow users to read all declared variabled. To block several variables use an array with in_array().
This is how I deal with getting/setting my properties, if you want to make Value() readonly ... then you simply just have it do the following instead:
Where as the function Value() right now would either get or set.