$result = $db->limit('0,10')->order('id desc')->findall();
“->”只能用于访问对象中的方法,所以 limit 和 order 肯定都返回的是对象。
第一种:不使用__call()
<?php class db { private $sql = array( "from" => "", "where" => "", "order" => "", "limit" => "" ); public function from($tableName) { $this->sql["from"]="$tableName"; return $this; } public function where($where='1=1') { $this->sql["where"]="$where"; return $this; } public function order($order='id DESC') { $this->sql["order"]="BY $order"; return $this; } public function limit($limit='30') { $this->sql["limit"]="$limit"; return $this; } public function select($select='*') { $sql = "SELECT $select "; foreach ($this->sql as $key => $value) { $sql .= strtoupper($key)." $value "; } return $sql; } } $db =new db(); echo $db->from("testTable")->where("id=1")->order("id DESC")->limit(10)->select(); // 输出 SELECT * FROM testTable WHERE id=1 ORDER BY id DESC LIMIT 10 ?>
第二种:__call()
__call()是php类的默认魔法函数,在调用一个不存在的方法时候会调用 __call()
<?php class db { private $sql = array( "from" => "", "where" => "", "order" => "", "limit" => "" ); public function __call($func, $args) { if (in_array($func, array('form','where','order','limit'))) { $this->sql[$func] = $args; return $this; } } public function select($select='*') { $sql = "SELECT $select "; foreach ($this->sql as $key => $value) { $sql .= strtoupper($key)." $value "; } return $sql; } } $db =new db(); echo $db->from("testTable")->where("id=1")->order("BY id DESC")->limit(10)->select(); // 输出 SELECT * FROM testTable WHERE id=1 ORDER BY id DESC LIMIT 10 ?>