php面向对象中的魔术方法之__get()、__set()、__call()

在php的面向对象编程中,我们可以通过__get()、__set()、__call()来存取或调用未经定义的属性和成员方法,如当我们一不小心写入一个不存在或不可见的属性时,php就会执行类中的__set()方法,__set方法必须接收两个参数,用来存放试图写入的属性名称和属性值。以下是来源zendframework 类库中的一段代码,这里代码利用__get()、__set()来做错误信息处理逻辑。

    public function __get($name)
    {
        $method = 'get'.ucfirst($name);
        if (method_exists($this, $method)) {
            return call_user_func(array(&$this, $method));
        } else {
            require_once 'Zend/Gdata/App/Exception.php';
            throw new Zend_Gdata_App_Exception(
'Property ' . $name . '  does not exist');
        }
    }

    public function __set($name, $val)
    {
        $method = 'set'.ucfirst($name);
        if (method_exists($this, $method)) {
            return call_user_func(array(&$this, $method), $val);
        } else {
            require_once 'Zend/Gdata/App/Exception.php';
            throw new Zend_Gdata_App_Exception(
'Property ' . $name . '  does not exist');
        }
    }

__call()方法是当我们在调用类中一个不存在或不可见的方法时,php就会自动的调用类中的__call()方法,__call()也必须接收两个参数,用来存放调用的方法名称和参数。php5.3中又定义__callStatic()方法,就是在调用一个不存在的静态方法时自动调用。

 function __call($name, $args){
     $op = $this->getOperation($name);
     array_unshift($args, $this);
     return call_user_func_array(array($op, 'execute'), $args);
 }
 

评论列表

  • 暂无评论,快说两句吧

发表评论

(必填)
(便于交流,可选)
  (支持Ctrl+Enter快捷回复)