php框架使用 __call() 实现连贯查询思路

Table of Contents

代码

class Test {
    protected $_options = array();
    public static $_method_array = array(
        'from', 'field', 'join', 'order', 'where'
    );

    public function __construct(){
        /**/
    }

    public function __call($func_name, $func_args){
        if(in_array($func_name, self::$_method_array)){
            $this->_options[$func_name] = $func_args;
        }
        return $this;
    }

    public function viewSql() {
        $sql = 'select '.$this->_options['field'][0].' from '.
             $this->_options['from'][0];
        echo $sql;
    }
}

$test = new Test();
$test->field('*')->from('test')->viewSql();

输出

➜  php php study_notes.php
select * from test

Author: josephzeng

Last Updated 2016-04-11. Created by Emacs 24.5.1 (Org mode 8.2.10)

Validate