批改状态:合格
老师批语:
1.静态绑定的原理与使用场景分析
代码在执行时分为两个阶段,第一阶段是编译阶段,第二阶段是运行阶段,
对于在运行阶段才能确定谁是调用者的技术称为后期静态绑定技术.
后期静态绑定出现主要是解决了当父类和子类中都存在同名的方法.使用者想要调用该同名的方法时候无法正确的识别当前想要调用方法.当使用后期静态绑定的时候就可以确定想要调用的方法.
2.链式操作
对于链式操作,其实就是链式调用对象的方法,以下是我的代码,
<?php
class mysql//创建一个接口
{
public static function __callStatic($name, $value)
{
return call_user_func_array([(new Query()),$name],$value);
}
}
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=php','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);
}
}
$mysql = mysql::table('staff')
->fields('id,name,age,salary')
->where('salary > 4000')
->select();
//print_r($result);
usort($mysql,function ($a,$b)
{
return strcmp($a['salary'], $b['salary']);//排序得出的结果
});
$table = '<table border="1" cellpadding="5" cellspacing="0" width="60%" align="center">';
$table .= '<caption style="font-size: 30px;margin:15px;">员工信息表</caption>';
$table .= '<tr bgcolor="#90ee90"><th>ID</th><th>姓名</th><th>年龄</th><th>工资</th></tr>';
foreach ($mysql as $c) {
$table .= '<tr align="center">';
$table .= '<td>'.$c['id'].'</td>';
$table .= '<td>'.$c['name'].'</td>';
$table .= '<td>'.$c['age'].'</td>';
$table .= '<td>'.$c['salary'].'</td>';
$table .= '</tr>';
}
$table .= '</table>';
$num = '<p style="text-align: center"> 共计: <span style="color:red">'.count($mysql).'</span> 条记录</p>';
echo $table, $num;点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号