使用静态方法的重载技术, 实现一个数据库访问类,并实例演示链接调用的实现过程
<?php
require 'select.php';
class Db{
protected static $pdo =null;
public static function connection(){
self::$pdo=new PDO('mysql:host=127.0.0.1;dbname=admin',root,root);
}
public static function __callStatic($name, $arguments)
{
// TODO: Implement __callStatic() method.
self::connection();
$select = new Select(self::$pdo);
return call_user_func_array([$select,$name],[$arguments[0]]);
}
}
$users = Db::table('user')
->field('id,name,sex')
->where('id < 10')
->limit(5)
->select();
// 遍历查询结果
foreach ($users as $user) {
print_r($user); echo '<br>';
}<?php
class Select{
public $pdo = null;
public $table = '';
public $field='';
public $where ='';
public $limit = 0;
//初始化连接对象
public function __construct($pdo)
{
$this->pdo=$pdo;
}
public function table($table){
$this->table=$table;
return $this;
}
public function field($fields){
$this->field=$fields;
return $this;
}
public function where($where)
{
$this->where = $where;
return $this;
}
public function limit($limit)
{
$this->limit = $limit;
return $this;
}
public function selectmethod()
{
$fields = empty($this->field) ? '*' : $this->field;
$where = empty($this->where) ? '' : ' WHERE '.$this->where;
$limit = empty($this->limit) ? '' : ' LIMIT '.$this->limit;
// 接装SQL语句
$sql = 'SELECT '.$fields.' FROM '.$this->table. $where . $limit;
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
?>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号