PHP Readonly Properties?

You can do it like this:

class Example {
    private $__readOnly = 'hello world';
    function __get($name) {
        if($name === 'readOnly')
            return $this->__readOnly;
        user_error("Invalid property: " . __CLASS__ . "->$name");
    }
    function __set($name, $value) {
        user_error("Can't set property: " . __CLASS__ . "->$name");
    }
}

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.

Leave a Comment