批改状态:合格
                        老师批语:
                    
                            一、概述
本节课主要讲述了方法重载,call_user_func_array()、静态后期绑定
二、作业
用call_user_func_array()模拟TP框架链式查询。
Queiry.php
<?php
/*
 * query
 *
 */
class Query{
    //selsect fields from table where ....limit 5;
    private $sql = [];
    private $pdo = null;
    //连接数据库
    public function __construct()
    {
        $this->pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root');
    }
    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']}";
        $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);
    }
}Db.php
<?php
require 'Query.php';
//数据库操作入口,call_user_func_array([类名/对象,方法],[$args])
class Db{
    public static function __callStatic($name, $arguments)
    {
       return call_user_func_array([(new Query()),$name],$arguments);
    }
}
//输入数据进行查询
$result = Db::table('staff')
        ->fields('name,sex,age,salary')
        ->where('salary>3000')
        ->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="#ff7f50"><th>姓名</th><th>性别</th><th>年龄</th><th>工资</th></tr>';
foreach ($result as $item) {
    $table .= '<tr align="center">'.'<td>'.$item['name'].'</td>';
    $table .= '<td>'.$item['sex'].'</td>';
    $table .= '<td>'.$item['age'].'</td>';
    $table .= '<td>'.$item['salary'].'</td>';
}
$table .= '</table>';
$num = '<p style="text-align: center">共计<span style="color: coral">'.count($result).'</span>条数据</p>';
echo $table,$num;点击 "运行实例" 按钮查看在线实例
结果图:

静态后期绑定
<?php
class A {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        static::who(); // 后期静态绑定从这里开始
    }
}
class B extends A {
    public static function who() {
        echo __CLASS__;
    }
}
B::test();
?>点击 "运行实例" 按钮查看在线实例
结果应该是B

三、总结
return __METHOD__; // 返回当前方法名
call_user_func_array():执行方法或回调函数
call_user_func_array(函数/方法[, 参数数组])
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号