Correction status:qualified
Teacher's comments:
利用__callStatic()魔术方法和call_user_func_array()模仿tp框架的链式查询;
<?php class Conn{ private $pdo = null; private $config = [ 'type'=>'mysql', 'host'=>'localhost', 'user'=>'abc', 'pwd'=>'abc', 'db_name'=>'test', ]; private $talbe; private $field; private $where; function __construct(){ $this->pdo = new PDO("mysql:host=localhost;dbname=test",$this->config['host'],'abc'); } //连接数据结束 public function table($table){ $this->table = $table; //返回对象本身 return $this; } public function field($field){ $this->field = $field; return $this; } public function where($where){ $this->where = $where; return $this; } public function select(){ $sql = "SELECT $this->field FROM `{$this->table}` WHERE {$this->where}"; echo $sql; $stmt = $this->pdo->prepare($sql); $stmt->execute(); return $stmt->fetchAll(PDO::FETCH_ASSOC)[0]; } } class Db{ public static function __callStatic($name,$value){ //调用Conn对象处理table()并返回最后结果 return call_user_func_array([(new Conn()),$name], $value); } } // DB::table('user')->field('id,name,pwd')->where('id=2')->select(); $res = Db::table('user')->field('id,name,pwd')->where('id=2')->select(); echo "id为",$res['id'],'姓名',$res['name'],'密码',$res['pwd']; ?>
点击 "运行实例" 按钮查看在线实例
后期静态绑定的原理与使用场景分析: