批改状态:合格
老师批语:
1.链式调用
使用重载方法和call_user_func_array()来模拟tp框架的链式调用。个人认为链式调用其实就是每个方法执行相应的数据操作然后返回当前对象。代码如下:
//Db::table()->fields()->where()->select()
class Query{
protected static $pdo = null;
//连接数据库的参数
private $data = [
'type' => 'mysql',
'host' => 'localhost',
'dbname' => 'php',
'user' => 'root',
'pass' => 'root'
];
//保存sql语句中的各个部分
private $sql = [];
//构造器 连接数据库
public function __construct()
{
$dsn = $this->data['type'].':host='.$this->data['host'].';dbname='.$this->data['dbname'];
$user = $this->data['user'];
$pass = $this->data['pass'];
self::$pdo =new PDO($dsn,$user,$pass);
self::$pdo->query('set names utf8');
}
//设置表名
public function table($table){
$this->sql['table'] = $table;
return $this;//返回当前对象
}
//设置字段名
public function fields($fields){
$this->sql['fields'] = $fields;
return $this;
}
//设置条件
public function where($where){
$this->sql['where'] = $where;
return $this;
}
//查询操作
public function select(){
$sql = "SELECT {$this->sql['fields']} FROM {$this->sql['table']} WHERE {$this->sql['where']};";
$stmt = self::$pdo->prepare($sql); //创建预处理对象
$stmt->execute();//执行语句
return $stmt->fetchAll(PDO::FETCH_ASSOC);//返回结果集
}
}
class Db{
public static function __callstatic($name, $arguments){
//调用query的成员方法
return call_user_func_array([new Query(), $name], $arguments);
// return (new query())->$name($arguments[0]);
}
}
//获取查询结果
$where = 'salary>'.$_GET['salary'];
$res = Db::table('staff')->fields('staff_id,name,salary')->where($where)->select();
$table = '<form action="" method="get"><h3 align="center">工资大于:<input type="text" name="salary" value=""> <button>提交</button></h3></form>';
$table .= '<table border="1" align="center" cellpadding="5px" cellspacing="0" width="30%"><caption style="font-size: 1.5rem;margin: 5px">员工信息表</caption>';
$table .= '<tr align="center" bgcolor="#87ceeb"><th>id</th><th>姓名</th><th>工资</th>';
foreach ($res as $staff){
$table .= "<tr align='center'><td>{$staff['staff_id']}</td>";
$table .= "<td>{$staff['name']}</td>";
$table .= "<td>{$staff['salary']}</td></tr>";
}
$table .= '</table>';
echo $table;点击 "运行实例" 按钮查看在线实例
2.后期静态绑定
原理:后期就是代码的运行过程中,而前期就是代码编写过程。后期静态绑定是为了静态继承中能够动态设置静态方法的调用者。使用static作为伪变量而不是self,self只是绑定当前的类,并不能识别出子类的的调用,而static就可以识别出调用者,从而可以调用子类的方法而不是父类的方法
使用场景:在静态继承中,子类重写了父类的静态方法时,需要调用子类的静态方法时就要使用static这个为变量。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号