作业问题:
代码:
<?php
class Query
{
//创建类的唯一实例
private static $db;
protected $table;
protected $field;
protected $limit;
private function __construct()
{
}
static function connect($dsn,$username,$pwd)
{
if(is_null(static::$db)){
static::$db = new PDO($dsn,$username,$pwd);
}
//返回query实例
return new static();
}
public function table($table)
{
$this->table = $table;
// echo $this->table;
return $this;
}
public function field($field)
{
$this->field = $field;
// echo $this->field;
return $this;
}
public function limit($limit)
{
$this->limit = $limit;
return $this;
}
public function getSql()
{
return 'SELECT '.$this->field.' FROM '.$this->table.' LIMIT '.$this->limit;
// 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, $arygs)
{
$dsn = 'mysql:host=localhost;dbname=test_db';
$username = 'test_db';
$pwd = '123456';
//获取委托实例
$query = Query::connect($dsn,$username,$pwd);
return call_user_func([$query,$method],...$arygs);
}
}
//$res = Db::table('t_user')
// ->field('name')
// ->limit(1)
// ->select();
//
//print_r($res);
print_r(Db::filed('nihao'));