批改状态:合格
老师批语:
使用方法重载与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::来调用,这样在后期的话,可以调用父类自身的属性或方法,也可以调用子类自身的属性或方法,不会导致逻辑处理错误.
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号