Calling the variable property directly vs getter/setters - OOP Design

后端 未结 7 819
-上瘾入骨i
-上瘾入骨i 2021-01-17 09:31

I know this is probably subjective but I read this optimization page from Google for PHP and they suggest use the variable property directly without the need of getters and

7条回答
  •  花落未央
    2021-01-17 10:21

    You could also use the __get and __set magic methods:

    class Example
    {
        private $allowedProps = array('prop1', 'prop2', 'prop3');
        private $data = array();
    
        public function __set($propName, $propValue)
        {
            if (in_array($propName, $this->allowedProps))
            {
                $this->data[$propName] = $propValue;
            }
            else
            {
                // error
            }
        }
    
        public function __get($propName)
        {
            if (array_key_exists($propName, $this->data))
            {
                return $this->data[$propName];
            }
            else
            {
                // error
            }
        }
    }
    

提交回复
热议问题