博主信息
博文 43
粉丝 0
评论 0
访问量 33648
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
链式查询和期静态绑定的原理+2018年9月4日
Lee的博客
原创
758人浏览过

使用方法重载与call_user_func_array()模拟TP框架的链式查询

实例

<?php
class Query{
    // 保存sql语句中的各个组成部分
    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查询语句
        // SELECT 字段列表 FROM 表名 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);
    }
}

运行实例 »

点击 "运行实例" 按钮查看在线实例


实例

<?php
// Db::table()->fields()->where()->select();
require 'Query.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('staff')
             ->fields('staff_id,name,age,salary')
             ->where('staff_id <= 10')
             ->select();

// 用表格将查询结果格式化输出
$table = '<table border = "1" cellpadding = "6" cellspacing = "0" width = "65%" align = "center">';
$table .= '<caption style = "font-size:1.6rem;margin:15px;">员工信息表</caption>';
$table .= '<tr bgcolor="grey;"><th>ID</th><th>姓名</th><th>年龄</th><th>工资</th></tr>';

foreach ($result as $staff){
    $table .= '<tr align ="center">';
    $table .= '<td>'.$staff['staff_id'].'</td>';
    $table .= '<td>'.$staff['name'].'</td>';
    $table .= '<td>'.$staff['age'].'</td>';
    $table .= '<td>'.$staff['salary'].'</td>';
    $table .= '</tr>';
}

$table .= '</table>';
$num = '<p style = "text-align:center">共计:<span style="color:purple">'.count($result).'</span> 条记录</p>';
echo $table,$num;

运行实例 »

点击 "运行实例" 按钮查看在线实例


QQ截图20180905162001.png


后期静态绑定的原理与使用场景分析

引入后期静态绑定的目的是:用于在继承范围内引用静态调用的类。
所以, 可以用后期静态绑定的办法解决单例继承问题。


批改状态:未批改

老师批语:
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学