Correcting teacher:灭绝师太
Correction status:qualified
Teacher's comments:
作业标题: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);