PHP实现的连贯操作、链式操作实例
PHP中的连贯操作看起来的确很酷,也非常的方便代码的阅读,当然了必须是在OOP中用才行,在过程化的程序中,就没有必要用这种方法了。有实现这个方法的有用_CALL来实现的,而我下面写的这个例子,则不是用_call的,大家可以扩展一下吧。
下面写的这个SQL语句组合类,主要是用于学习的,如果有同学想拿去用,请再完善一下。
/*
*SQL语句组合实例类,始发文章web开发笔记
*学习用,非专业类
**/
classsql{
private$sql=array("from"=>"",
"where"=>"",
"order"=>"",
"limit"=>"");
publicfunctionfrom($tableName){
$this->sql["from"]="FROM".$tableName;
return$this;
}
publicfunctionwhere($_where='1=1'){
$this->sql["where"]="WHERE".$_where;
return$this;
}
publicfunctionorder($_order='idDESC'){
$this->sql["order"]="ORDERBY".$_order;
return$this;
}
publicfunctionlimit($_limit='30'){
$this->sql["limit"]="LIMIT0,".$_limit;
return$this;
}
publicfunctionselect($_select='*'){
return"SELECT".$_select."".(implode("",$this->sql));
}
}
$sql=newsql();
echo$sql->from("testTable")->where("id=1")->order("idDESC")->limit(10)->select();
//输出SELECT*FROMtestTableWHEREid=1ORDERBYidDESCLIMIT0,10