相信大家在用ThinkPHP开源框架的时候,对Model类的连贯操作方法肯定很感兴趣吧,那今天我们就用PHP中的__call()魔术方法去实现对SQL语句select的查询的连贯操作。
代码:
<?
header("Content-type:text/html;charset=utf-8");
class testcall{
public $p; /*记录SQL关键字*/
/*select * from table where id=1 order by id limit 1,2*/
function __call($method_name,$arg){
if(in_array($method_name,array('field','table','where','order','limit'))){
$this->p[$method_name]=$arg[0];
}
return $this; /*返回当前对象 testcall*/
}
function select(){
$field=isset($this->p['field'])?$this->p['field']:'*';
$table=isset($this->p['table'])?$this->p['table']:'default';
$where=isset($this->p['where'])?' where '.$this->p['where']:'';
$order=isset($this->p['order'])?' order by '.$this->p['order']:'';
$limit=isset($this->p['limit'])?' limit '.$this->p['limit']:'';
$sql='select '.$field.' from '.$table.$where.$order.$limit;/*组合SQL语句*/
return $sql;
}
}
$obj=new testcall();
echo $obj->field('field1')->table('table1')->where('id=1')->select();/*连贯操作方法*/
?>
以上代码输出
select field1 from table1 where id=1
来源:oschina
链接:https://my.oschina.net/u/121743/blog/97983