Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
<?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);
?>