Blogger Information
Blog 34
fans 0
comment 0
visits 32251
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
使用方法重载与call_user_func_array()模拟TP框架的链式查询+后期静态绑定的原理与使用场景分析
Belifforz的博客
Original
688 people have browsed it
  1. 使用方法重载与call_user_func_array()模拟TP框架的链式查询

实例

<?php
/*
 *模仿TP框架链式查询
 *
 *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);
    }
}

$result = Db::table('staff')
            ->fields('id,name,salary')
            ->where('salary>3000')
            ->select();
echo '<pre>';
print_r($result);

运行实例 »

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

实例

<?php


class Query
{
    private  $pdo = null;
    private $sql = [];
    public function __construct(){
        //连接数据库
        $this->pdo = new PDO('mysql:host=127.0.0.1;dbname=php','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语句
        $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);
   

    }

}

运行实例 »

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


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


后期静态绑定用static::functionname()  或者static::$name来绑定,当子类继承父类,而用子类调用父类方法里面的父类方法或者属性时,就需要用到后期静态绑定.


场景分析:

当子类继承父类,而子类又重写了父类的方法,方法里面调用到自身属性或者方法时,

需要在方法里面用static::来调用,这样在后期的话,可以调用父类自身的属性或方法,也可以调用子类自身的属性或方法,不会导致逻辑处理错误.


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