批改状态:合格
老师批语:
<?php/*** 事件委托:数据库查询构造器*///被委托的类class Query{//创建类的唯一实例 :pdo对象private static $db;protected $table;protected $field;protected $limit;//private 私有的 阻止此类在外部进行实例化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:localhost;dbname=yu';$username = 'root';$pwd ='123456yu';//获取到被委托的类query实例$query = Query::connect($dsn,$username,$pwd);return call_user_func([$query,$method],...$args);}}$res = Db::table('cate')->field('catname,catid')->limit(5)->select();echo '<pre>';print_r($res);?>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号