批改状态:合格
老师批语:
1. 编程: 使用方法重载与call_user_func_array()模拟TP框架的链式查询

<?php
// 方法重载实战案例:模拟TP5.1中的数据库链式操作
//Db::table()->fields()->where()->select();
//用方法重载实现跨类调用
require 'Query1.php';
//数据库操作的入口类
class Db
{
public static function __callStatic($name,$arguments)
{
//call_user_func_array([类名,方法],[]);
//call_user_func_array([对象,方法],[]);
return call_user_func_array([(new Query()),$name],$arguments);
}
}
$result = Db::table('user')->fields('id,name,email')->where('id > 1')->select();
//print_r($result);
// 用表格将查询结果格式化输出
$table = '<table border="1" cellpadding="5" cellspacing="0" width="60%" align="center">';
$table .= '<caption style="font-size: 1.5rem;margin:15px;">用户信息表</caption>';
$table .= '<tr bgcolor="#90ee90"><th>ID</th><th>姓名</th><th>邮箱</th></tr>';
foreach ($result as $user)
{
$table .= '<tr align="center">';
$table .= '<td>'.$user['id'].'</td>';
$table .= '<td>'.$user['name'].'</td>';
$table .= '<td>'.$user['email'].'</td>';
$table .= '</tr>';
}
$table .= '</table>';
$num = '<p style="text-align: center"> 共计: <span style="color:red">'.count($result).'</span>条记录</p>';
echo $table, $num;点击 "运行实例" 按钮查看在线实例
<?php
//数据库查询类
class Query
{
//保存sql语句中的各个组成部门
//SELECT 字段列表 FROM 表名 WHERE 条件
private $sql = [];
//数据库的连接对象
private $pdo = null;
//构造方法:连接数据库
public function __construct()
{
//连接数据库并返回pdo对象
$this->pdo = new PDO('mysql:host=127.0.0.1;dbname=edu','root','root');
}
//table()获取sql语句的表名
public function table($table)
{
$this->sql['table'] = $table;
return $this;//返回当前类实例对象,便于链式调用该对象的其它方法
}
//fields()获取sql语句的字段名
public function fields($fields)
{
$this->sql['fields'] = $fields;
return $this;
}
//where()获取sql语句的查询条件
public function where($where)
{
$this->sql['where'] = $where;
return $this;
}
//执行查询,是一个终极方法(跟上面会有一点点不一样)
public function select()
{
//拼装SELECT查询语句
$sql = "SELECT {$this->sql['fields']} FROM {$this->sql['table']} WHERE {$this->sql['where']}";
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}点击 "运行实例" 按钮查看在线实例
2. 问答: 后期静态绑定的原理与使用场景分析
后期静态绑定的原理:当子类调用父类同名方法并在子类进行了重写,通过static进行静态绑定,始终指向静态方法的调用者。
后期静态绑定的使用场景分析:当子类需要对父类同名方法重写并调用的时候
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号