首页  >  文章  >  后端开发  >  PDO单例模型

PDO单例模型

巴扎黑
巴扎黑原创
2016-11-24 14:19:541308浏览

<?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(&#39;DB_HOST&#39;,   &#39;localhost&#39;);
define(&#39;DB_PORT&#39;,   &#39;3306&#39;);
define(&#39;DB_USER&#39;,   &#39;root&#39;);
define(&#39;DB_PASSWD&#39;, &#39;123456&#39;);
define(&#39;DB_CHARSET&#39;,&#39;utf8&#39;);
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 = &#39;mysql:host=&#39;.DB_HOST.&#39;;port=&#39;.DB_PORT.&#39;;dbname=&#39;.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();
?>


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn