写一个数据库操作类, 要求用到命名空间, 类继承, 后期绑定访问, 来实现数据表的简单访问
实例
<?php namespace Test; use PDO; if (!interface_exists(__NAMESPACE__.'\iDbParam')) { interface iDbParam { const TYPE = 'mysql'; const HOST = 'localhost'; const USER_NAME = 'root'; const PASSWORD = 'root'; const DBNAME = 'php'; public static function Connection (); } } class Connection implements namespace\iDbParam { // 初始化连接参数 private static $type = iDbParam::TYPE; private static $host = iDbParam::HOST; private static $userName = iDbParam::USER_NAME; private static $password = iDbParam::PASSWORD; private static $dbname = iDbParam::DBNAME; public static function Connection() { $dsn = self::$type.':host='.self::$host.';dbname='.self::$dbname; $user = self::$userName; $password = self::$password; $pdo = new PDO($dsn,$user,$password); return $pdo; } } //类的继承 class Db extends Connection { //连接对象 protected $pdo=null; //数据表 protected $table='staff'; //读取数据 public function read($fields='*', $where='', $limit='0, 5') { // 设置查询条件 $where = empty($where) ? '' : ' WHERE ' . $where; // 设置显示数量 $limit = ' LIMIT ' . $limit; //以后连接数据库只需要这个静态方法即可,注意命名空间 $link = Connection::Connection(); // 预处理查询操作 $sql = 'SELECT '.$fields.' FROM '.$this->table.$where.$limit; $stmt = $link->prepare($sql); $stmt->execute(); // $stmt->debugDumpParams();die; // 返回二维数组表示的查询结果集 return $stmt->fetchAll(PDO::FETCH_ASSOC); } //获取信息 public function getInfo() { foreach ($this->read('staff_id, name, position', 'age > 30','0,10') as $item) { print_r($item); echo '<br>'; } } } // 实例化子类Db $db=new Db(); $db->getInfo(); echo '<hr>'; echo Db::class,'<br>'; echo get_class($db),'<br>'; echo '<hr>'; namespace test2; // 命名空间别名 //use code\inc\Class1 as Class1; use code\inc\Class1;// 如果省略as,取\后面的名字 use code\inc\Class2; //自动加载 //spl_autoload_register(function ($class){ // include __DIR__ . '/code/inc/' .$class.'.php'; //// include __DIR__ . '/code/inc/Class1.php'; //// include __DIR__ . '/code/inc/Class2.php'; //}); include 'code/inc/Class1.php'; include 'code/inc/Class2.php'; $obj1=new Class1(); echo get_class($obj1).'<br>'; $obj2=new Class2(); echo get_class($obj2); echo '<hr>';
运行实例 »
点击 "运行实例" 按钮查看在线实例