欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PDO单例模型

程序员文章站 2022-03-31 16:59:33
...
<?php
/**
 * ipdo.php
 *
 * discription
 *
 * @filename ipdo.php
 * @version  v1.0
 * @update   2011-4-27
 * @author   randy.hong
 * @contact homingway@163.com
 * @package  pdo
 */
//DB config
define('DB_HOST',   'localhost');
define('DB_PORT',   '3306');
define('DB_USER',   'root');
define('DB_PASSWD', '123456');
define('DB_CHARSET','utf8');
class IPDO {
    /**
     * The singleton instance
     */
    static public $PDOInstance;
  /**
   * Creates a PDO instance representing a connection to a database and makes the instance available as a singleton
   * @return PDO
   */
    public function __construct(){
    $dsn = 'mysql:host='.DB_HOST.';port='.DB_PORT.';dbname='.DB_NAME;
    $driver_options = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES ".DB_CHARSET);
        if(!self::$PDOInstance) {
       try {
               self::$PDOInstance = new PDO($dsn, DB_USER, DB_PASSWD, $driver_options);
               self::$PDOInstance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch (PDOException $e) {
                die($e->getMessage());
            }
    }
      return self::$PDOInstance;
    }
}
//使用
$pdo = new IPDO();
?>