利用静态方法重载函数实现数据库的访问查询。
在访问一个静态的不存在的类方法的时候,如果该方法不存在就会触发一个魔术方法 静态重载函数
利用这个函数为入口掉用Query类,实现对数据库的连接操作,
Query类每次都返回当前类的对象this,方便与链式调用Query类的其他属性或者方法。
静态重载代码
<?php
require 'Query.php';
class Db
{
// 数据链接对象
protected static $pdo = null;
// 数据链接方法,每次查询时再链接,实现真正的惰性连接,节省系统开销
public static function connection()
{
self::$pdo = new PDO('mysql:host=localhost;dbname=php','root','root');
}
// 静态方法的重载
public static function __callStatic($name, $arguments)
{
// 连接数据库
self::connection();
// 实例化查询类
$query = new Query(self::$pdo);
return call_user_func_array([$query,$name],[$arguments[0]]);
}
}
echo '<hr>';
//静态方法就不需要new
$cats = Db::table('category')//调用Db类的静态方法重载 会返回Query对象
->field('cate_id,alias')//调用Query对象field方法
->where('cate_id >= 1')//调用Query对象where方法
// ->limit(2)
->select(); //调用Query对象select方法
foreach ($cats as $cat)
{
print_r($cat);
echo '<br>';
}点击 "运行实例" 按钮查看在线实例
Query类代码
<?php
class Query
{
// 连接对象
public $pdo = null;
// 数据库名称
public $table = '';
// 字段列表
public $field ='';
// 查询条件
public $where ='';
// 查询数量
public $limit = 0;
// 构造方法
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
// 数据库名称
public function table($table)
{
$this->table = $table;
return $this; //this代表当前对象 返回后方面链式调用
}
// 字段列表
public function field($fields)
{
$this->field = $fields;
return $this; //this代表当前对象 返回后方面链式调用
}
// 查询条件
public function where($where)
{
$this->where = $where;
return $this; //this代表当前对象 返回后方面链式调用
}
// 查询数量
public function limit($limit)
{
$this->limit = $limit;
return $this; //this代表当前对象 返回后方面链式调用
}
// 创建SQL语句
public function select()
{
// 设置查询条件
$fields =empty($this->field) ? '*' : $this->field;
$where=empty($this->where) ? '' : ' WHERE '.$this->where;
$limit=empty($this->limit) ? '' : ' LIMIT '.$this->limit;
$sql = 'SELECT '.$fields.' FROM '.$this->table.$where.$limit;
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号