Home > Backend Development > PHP Tutorial > php call()方法实现数据库连贯操作

php call()方法实现数据库连贯操作

WBOY
Release: 2016-06-20 12:35:25
Original
1075 people have browsed it

背景:对的jquery有一种叫链式操作的dom的,而PHP在写sql时也可以使用类似的方法,如:

/*      * 从数据库获得用户分页专辑记录      *      * @param str|array   $where   查询条件      * @param int   $page    当前页      * @param int   $perpage 每页显示的记录数      * @param str   $order   排序类型      * @param str   $asc     升序/降序      * @return array         满足条件的记录     /     public function getUsersAlbumFromDB($where, $page, $perpage, $order, $asc)     {         $offset = ($page - 1) * $perpage;         $dataList = $this->getSelectObj()                          ->where($where)                          ->order($order, $asc)                          ->limit($perpage, $offset)                          ->fetchObject();         return $dataList;     }

这种写法有点类似Jquery的链式写法,如下:

$ (this).find ("div").css ("background", "red").end().siblings ().find ("div").css ("background", "green");
Copy after login

__call函数相关介绍:http://justwinit.cn/post/2834/

=================================================

使用__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();?>
Copy after login

---------- 调试PHP ----------

SELECT sex, count(sex) FROM  user where sex in ("男","女")   group by sex

having avg(age) > 25

Output completed (0 sec consumed) - Normal Termination

来自:http://blog.sina.com.cn/s/blog_6109978501017154.html

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template