实例
<?php /** * 模拟tp5中的数据查询链式操作 * Db::table()->fields()->where()->select(); */ require ('Query.php'); class Db{ public static function __callStatic($name, $arguments) { return call_user_func_array([(new Query()),$name],$arguments); } } $res = Db::table('stuclass') ->fields('id,name,age') ->where('classid=1') ->select(); $table = '<table cellspacing="0" cellpadding="0" border="1" width="300"><tr><th>ID</th><th>姓名</th><th>地址</th></tr>'; $table .= '<caption>学生班级表</caption>'; foreach ($res as $value) { $table .= "<tr align='center'><td>{$value['id']}</td><td>{$value['name']}</td><td>{$value['age']}</td></tr>"; } $table .='</table>'; echo $table; /***********下面是query.php 文件*******************/ class Query{ //$sql private $sql=[]; private $pdo; function __construct() { $this->pdo = new PDO('mysql:host=127.0.0.1;dbname=stu','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']}"; $stmt = $this->pdo->prepare($sql); $stmt ->execute(); $row = $stmt->fetchAll(PDO::FETCH_ASSOC); return $row; } }
运行实例 »
点击 "运行实例" 按钮查看在线实例
后期静态绑定的原理与使用场景分析:
代码的执行分两个阶段:编译阶段、运行阶段;
在运行阶段才确定方法的调用者的技术叫静态绑定;
后期静态绑定:静态继承的上下文环境,用于动态设置静态方法的调用者