PHP Readonly Properties?

前端 未结 6 1209
闹比i
闹比i 2020-12-05 06:12

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 DOMNo

6条回答
  •  情歌与酒
    2020-12-05 07:02

    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.

提交回复
热议问题