PHP實現鏈式操作
阿新 • • 發佈:2019-01-01
php鏈式操作的關鍵是在做完操作後要return $this;
一、不使用__call方法實現鏈式操作
<?php
class Sql{
private $sql=array("from"=>"",
"where"=>"",
"order"=>"",
"limit"=>"");
public function from($tableName) {
$this->sql["from"]="FROM ".$tableName;
return $this;
}
public function where($_where='1=1') {
$this->sql["where"]="WHERE ".$_where;
return $this;
}
public function order($_order='id DESC') {
$this->sql["order"]="ORDER BY ".$_order;
return $this;
}
public function limit($_limit='30' ) {
$this->sql["limit"]="LIMIT 0,".$_limit;
return $this;
}
public function select($_select='*') {
return "SELECT ".$_select." ".(implode(" ",$this->sql));
}
}
$sql =new Sql();
echo $sql->from("testTable")->where("id=1")->order("id DESC")->limit(10 )->select();
//輸出 SELECT * FROM testTable WHERE id=1 ORDER BY id DESC LIMIT 0,10
?>
二、使用__call方法實現鏈式操作
__call()在物件呼叫一個不可訪問的方法時會被觸發,所以可以實現類的動態方法的建立,實現php的方法過載功能,但它其實是一個語法糖(__construct()方法也是)。
<?php
class String
{
public $value;
public function __construct($str=null)
{
$this->value = $str;
}
public function __call($name, $args)
{
$this->value = call_user_func($name, $this->value, $args[0]);
return $this;
}
public function strlen()
{
return strlen($this->value);
}
}
$str = new String('01389');
echo $str->trim('0')->strlen();
// 輸出結果為 4;trim('0')後$str為"1389"
?>