Blogger Information
Blog 48
fans 0
comment 0
visits 36354
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
使用方法重载与call_user_func_array()模拟TP框架的链式查询-2018.09.04
雨天的博客
Original
555 people have browsed it

实例

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

}

运行实例 »

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


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

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

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

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


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!