When do/should I use __construct(), __get(), __set(), and __call() in PHP?

后端 未结 10 706
再見小時候
再見小時候 2020-12-05 08:16

A similar question discusses __construct, but I left it in my title for people searching who find this one.

Apparently, __get and __set take a parameter that is the

10条回答
  •  既然无缘
    2020-12-05 08:59

    Overloading methods is especially useful when working with PHP objects that contain data that should be easily accessable. __get() is called when accessing a non-existent propery, __set() is called when trying to write a non-existent property and __call() is called when a non-existent method is invoked.

    For example, imagine having a class managing your config:

    class Config
    {
        protected $_data = array();
    
        public function __set($key, $val)
        {
            $this->_data[$key] = $val;
        }
    
        public function __get($key)
        {
            return $this->_data[$key];
        }
    
        ...etc
    
    }
    

    This makes it a lot easier to read and write to the object, and gives you the change to use custom functionality when reading or writing to object. Example:

    $config = new Config();
    $config->foo = 'bar';
    
    echo $config->foo; // returns 'bar'
    

提交回复
热议问题