read-only properties in PHP?

前端 未结 4 608
清歌不尽
清歌不尽 2021-01-17 14:18

Is there a way to make a read-only property of an object in PHP? I have an object with a couple arrays in it. I want to access them as I normally would an array

<         


        
4条回答
  •  庸人自扰
    2021-01-17 15:16

    If you're using PHP 5+ you can do it with __set() and __get() methods.

    You have to define how they work but should do just this.

    Edit an example would be like this.

    class Example {
        private $var;
        public function __get($v) {
            if (is_array($v)) {
                foreach () {
                    // handle it here
                }
            } else {
                return $this->$v;
            }
        }
    }
    

    This might not be the "best" way of doing it but it'll work depending on what you need

提交回复
热议问题