链式调用:即是每次访问方法,返回当前类实例, 用来链式调用后面的其它方法
方法重载:
query.php
<?php
namespace _1008;
// 数据库查询类
class Query
{
// 连接对象
public $pdo = null;
// 表名
public $table;
// 字段
public $field = '*';
// 条件
public $where;
// 数量
public $limit;
// 构造方法
public function __construct($pdo)
{
// 实例时自动连接数据库
$this->pdo = $pdo;
}
// 设置数据表名称
public function table($tableName)
{
$this->table = $tableName;
//返回当前类实例, 用来链式调用后面的其它方法
return $this;
}
// 设置数据表字段
public function field($fields = '*')
{
$this->field = empty($fields) ? '*' : $fields;
return $this;
}
// 设置查询条件
public function where($where = '')
{
$this->where = empty($where) ? $where : ' WHERE '. $where;
return $this;
}
// 设置显示数量
public function limit($limit)
{
$this->limit = empty($limit) ? $limit : ' LIMIT '. $limit;
return $this;
}
// 生成SQL语句
public function select()
{
// SELECT * FROM table WHERE **** LIMIT n
// 拼装SQL
$sql = 'SELECT '
. $this->field // 字段列表
. ' FROM '
. $this->table // 数据表
. $this->where // 条件
. $this->limit; // 显示数量
// 预处理
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
// die($stmt->debugDumpParams()); // 查看生成的sql
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
}点击 "运行实例" 按钮查看在线实例
实现
<?php
namespace _1008;
require 'Query.php';
class DB
{
// 连接对象
protected static $pdo = null;
// 数据库的连接方法
public static function connection()
{
self::$pdo = new \PDO('mysql:host=127.0.0.1;dbname=php', 'root', 'root');
}
public static function __callStatic($name, $arguments)
{
// 连接数据库
self::connection();
// 实例化查询类,将连接对象做为参数
$query = new Query(self::$pdo);
// 调用查询对象$query中的对应的方法
return call_user_func_array([$query, $name],$arguments);
}
}
$staffs = DB::table('staff')
->field('staff_id,name,position,mobile')
->where('staff_id > 2')
->limit(5)
->select();
// 遍历
foreach ($staffs as $staff) {
print_r($staff); echo '<br>';
}点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号