Correcting teacher:灭绝师太
Correction status:qualified
Teacher's comments:
<?php
//定义一个接口
interface iDbBase
{
//数据库的操作增删查改
static function insert($db,$data);
static function select($db,$where[]);
static function delete($db,$where[]);
static function update($db, $data,$where[]);
// return $this;//实现链式调用
static function doConnect($dsn,$username,$password);
}
//抽象类使用php中的单利模式来连接数据库
abstract class aDb implements iDbBase
{
//返回pdo的链接对象
private function $instance;
//private阻止此类在外部进行实例化
private function __construct()
{
}
//只能由类的自身来进行实例化
static function doConnect($dsn,$username,$password){
//判断$instance是否是aDb类的对象。用instanceof
//self访问静态成员$instance
if(!self::$instance){
//实例化本类,传入连接参数。
self::$instance =new PDO($dsn,$username,$password)
}
return self::$instance;
}
//self单利模式继承
}
//工作类
class Db extends aDb
{
//数据库的操作增删查改
static function insert($db,$data){
}
static function select($db,$where['gender'=>1,'userid'=>2]){
//声明一个变量
$str="";
foreach($where as $k=>$v){
if(count($where)>1){
$str.=$k.'=' .$v.'and';
}
else{
$str.=$k.'=' .$v;
}
}
if(count($where)>1) {
$str=substr($str,0,strlen(strlen)-4);
}
else{
echo $str;
}
//limit限定查询表的条数
return $db->query("SELECT * FROM 'myid' WHERE $str LIMIT 2")->fetchAll(PDO::FETCH_ASSOC);
}
static function delete($db,$where['gender'=>1,'userid'=>2]){
return $db->query("SELECT * FROM 'myid' WHERE $str LIMIT 1")->fetchAll(PDO::FETCH_ASSOC);
}
}
//客户端代码
$config=[
'type'=> $type??'mysql',
'host'=> $host='host'??'localhost',
'dbname'=>$dbname='dbname'??'news',
'password'=>$password='password'??'123456tyi',
'username'=> $username='username'??'root',
];
$dsn=printf('%s:host', $config['type'],$config['host'],$config['dbname']);
$username=$config['username'];
$password=$config['password'];
//获取PDO连接对象
$db=Db::doConnect($dsn,$username,$password);
echo '<pre>';
print_r(Db::select($db));
?>