首页 » 后端 » PHP » 正文

PHP连贯查询操作的两种实现原理

发布者:站点默认
2015/10/13 浏览数(1,768) 分类:PHP PHP连贯查询操作的两种实现原理已关闭评论
$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
	?>
点击返回顶部
  1. 留言
  2. 联系方式