当前位置:Gxlcms > PHP教程 > PDO单例模型

PDO单例模型

时间:2021-07-01 10:21:17 帮助过:19人阅读

<?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();
?>

人气教程排行