批改状态:合格
老师批语:
作业标题:0816 oop编程-4
作业内容:请用请求委托原理封装查询构造器(只封装查询操作即可)
class Query{private static $db;protected $table;protected $field;protected $limit;private function __construct(){}static function connect($dsn,$username,$pwd){//创建PDO类的唯一实例 pdo对象if(is_null(static::$db)){static::$db = new PDO($dsn,$username,$pwd);}// 返回query实例return new static();}public function table($table){$this->table = $table;return $this;}public function field($field){$this->field = $field;return $this;}public function limit($limit){$this->limit = $limit;return $this;}public function getSql(){return sprintf('SELECT %s FROM %s LIMIT %d ',$this->field,$this->table,$this->limit);}public function select(){return static::$db->query($this->getSql())->fetchAll(PDO::FETCH_ASSOC);}}class Db{static function __callStatic($method,$args){$dsn = 'mysql:host=localhost;dbname=my_test';$username = 'root';$pwd = 'root';// 获取到被委托的类query实例$query = Query::connect($dsn,$username,$pwd);return call_user_func([$query,$method],...$args);}}$res = Db::table('emp')->field('ename,empno')->limit(5)->select();echo '<pre>';print_r($res);

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号