博客列表 >使用方法重载与call_user_func_array()模拟TP框架的链式查询-2018.09.04

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

雨天的博客
雨天的博客原创
2018年09月10日 14:57:10553浏览

实例

<?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;
    }

}

运行实例 »

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


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

代码的执行分两个阶段:编译阶段、运行阶段;

在运行阶段才确定方法的调用者的技术叫静态绑定;

后期静态绑定:静态继承的上下文环境,用于动态设置静态方法的调用者


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议