Jquery中文网 www.jquerycn.cn
Jquery中文网 >  脚本编程  >  php  >  正文 php中的__call方法

php中的__call方法

发布时间:2017-04-19   编辑:www.jquerycn.cn
本文详细介绍了,php编程中__call方法的用法,这是一个用途广泛的php魔术方法,调用一个对象中不存在的方法,__call 方法将会被自动调用。感兴趣的朋友参考下。

php中的__call方法,是php中常用的一个魔术方法。

__call 的作用:“PHP5 对象新增的一个专用方法 ,用来监视一个对象中的其它方法。
如果试着调用一个对象中不存在的方法,__call 方法将会被自动调用。”

例子:
 

复制代码 代码示例:
<!--?php
class MethodTest {
     public function __call($name, $arguments) {
        echo "Calling object method '$name' "
             . implode(', ', $arguments). "\n";
     }
}
$obj = new MethodTest;
$obj--->runTest('in object context');
 

运行结果:
Calling object method 'runTest' in object context

看到一个__call在实际开发中的应用。
比如在thinkphp的:lib->think->core->model.class.php文件里面(Model类)有这么一段代码:
 

复制代码 代码示例:
<?php
    /**
     +----------------------------------------------------------
     * 利用__call方法实现一些特殊的Model方法
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $method 方法名称
     * @param array $args 调用参数
     +----------------------------------------------------------
     * @return mixed
     +----------------------------------------------------------
     */
    public function __call($method,$args) {
        if(in_array(strtolower($method),array('field','table','where','order','limit','page','alias','having','group','lock','distinct'),true)) {
            // 连贯操作的实现
            $this-&gt;options[strtolower($method)] =   $args[0];
            return $this;
        }elseif(in_array(strtolower($method),array('count','sum','min','max','avg'),true)){
            // 统计查询的实现
            $field =  isset($args[0])?$args[0]:'*';
            return $this-&gt;getField(strtoupper($method).'('.$field.') AS tp_'.$method);
        }elseif(strtolower(substr($method,0,5))=='getby') {
            // 根据某个字段获取记录
            $field   =   parse_name(substr($method,5));
            $where[$field] =  $args[0];
            return $this-&gt;where($where)-&gt;find();
        }else{
            throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
            return;
        }
    }
 

调用方法:
 

复制代码 代码示例:
$this->dao= M(‘table’); //快速高性能实例化一个 table 表的模型
$this->dao->field($field)->where($where)->limit($offset . ‘,’ . $limit)->select();    //设置查询字段,查询条件,设置查询数量,最后执行查询操作。当然返回的就是数据库记录了。

说明:
field方法成对象了,where、limit、select方法也成对象了,其实field、where这些方法在 Model类 里面都不存在。
正是因为这些方法不存在,所以此时__call方法被执行,然后又会返回$this对象。
实现这种“衔接”写法,一行代码搞定了所有的SQL语句。

您可能感兴趣的文章:
有关PHP的__call学习参考
PHP中__call的用法实例
php中的__call方法
PHP5试用(二)
PHP三种方式实现链式操作
php __call、__set 和 __get的用法介绍
PHP使用redis作为缓存(高效技术)
php面向对象__call处理错误调用技巧
php链式操作的实现
php面试题目 面向中等水平的程序员

[关闭]