Heim  >  Artikel  >  Backend-Entwicklung  >  PDO-Singleton-Modell

PDO-Singleton-Modell

巴扎黑
巴扎黑Original
2016-11-24 14:19:541270Durchsuche

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


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn