php __call()方法实现数据库连贯操做

使用__call()方法来实现数据库连贯操做 <?php  // 使用__call()方法来实现数据库连贯操做  // 申明一个Db类(数据库操做类)的简单操做模型 class Db{    private $sql = array(       "field" => "",       "where" => "",       "order" => "",       "limit" => "",       "group" => "",       "having" => "",    );        // 连贯操做调用field() where() order() limit() group() having()方法,组合sql语句    function __call($methodName,$args){       // 将第一个参数(表明不存在方法的方法名称),所有转成小写方式,获取方法名称       $methodName = strtolower($methodName);              // 若是调用的方法名和成员属性数组$sql下标对应上,则将第二个参数给数组中下标对应的元素       if(array_key_exists($methodName,$this->sql)){          $this->sql[$methodName] = $args[0];       }else{          echo '调用类'.get_class($this).'中的方法'.$methodName.'()不存在';       }       // 返回本身对象,则能够继续调用本对象中的方法,造成连贯操做       return $this;    }    // 输出连贯操做后组合的一个sql语句,是连贯操做最后的一个方法    function select(){       echo "SELECT {$this->sql['field']} FROM user {$this->sql['where']} {$this->sql['order']} {$this->sql['limit']} {$this->sql['group']}             {$this->sql['having']}";    } } $db = new Db(); // 连贯操做 $db->field('sex, count(sex)')   ->where('where sex in ("男","女")')   ->group('group by sex')   ->having('having avg(age) > 25')   ->select(); ?>
相关文章
相关标签/搜索