codeigniter

php 的魔术方法__call()的应用

蓝咒 提交于 2020-10-24 16:02:57
php的魔术方法__call()是在访问对象中不存在的方法时会自动调用该方法,可以在该方法中给出错误提示信息反馈回调用用户。但是魔术方法__call()不只这样用,可以实现像codeIgniter的数据库查询构造器类的链式方法生成sql语句。 // codeIgniter的链式方法 $result = $this -> db ->select("*" ) ->from( $this -> dbTable) ->where('name', $name ) ->where('title', $title ) ->order_by('title', 'DESC' ) ->get(); 下面是用魔术方法__call()实现上面的链式方法 ——连贯操作 <? php // 声明一个DB类(数据库操作类)的简单操作模型 class DB{ private $sql = array ( 'field' => '', 'where' => '', 'order' => '', 'limit' => '', 'group' => '', 'having' => '' ); // 连贯操作调用field(),where(),order(),limit(),group(),having()方法,组合sql语句 function __call( $methodName , $arge ){ //