Blogger Information
Blog 38
fans 1
comment 0
visits 26347
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
类方法的重载--2018年09月5日15时30分
一根火柴棒的博客
Original
533 people have browsed it

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

实例

<?php

//Db::table('think_user')->field('id,name,email')->where('id',1)->select();

require 'query.php';

class Db
{

    public static function __callStatic($name, $arguments)
    {
        return call_user_func_array([new Query(),$name],$arguments);
    }
}


$result = Db::table('name')
            ->field('id,name,age')
            ->where('age > 0')
            ->select();


echo '<pre>';
print_r($result);


class Query
{
    //SELECT 字段列表 FROM 表名 WHERE 条件
    private $sql = [];

    private $pdo = null;

    public function __construct()
    {
        $this->pdo = new PDO('mysql:host=127.0.0.1;dbname=user','root','root');
    }


    //获取sql语句中的表名
    public function table($table)
    {
        $this->sql['table'] = $table;

        //返回实例对象;
        return $this;
    }

    public function field($field)
    {
        $this->sql['field'] = $field;

        //返回实例对象;
        return $this;
    }

    public function where($where)
    {
        $this->sql['where'] = $where;

        //返回实例对象;
        return $this;
    }

    public function select ()
    {
        //拼接查询语句
        $sql = "SELECT {$this->sql['field']} FROM {$this->sql['table']} WHERE {$this->sql['where']}";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

运行实例 »

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

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

后期静态绑定工作原理是存储了在上一个“非转发调用”(non-forwarding call)的类名。当进行静态方法调用时,该类名即为明确指定的那个(通常在 :: 运算符左侧部分);当进行非静态方法调用时,即为该对象所属的类

一般用于什么场景:最常见的一般用于查询语句

Correction status:qualified

Teacher's comments:
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