このページの2つのバージョン間の差分を表示します。
次のリビジョン | 前のリビジョン | ||
11_php:05_class:02_db_singleton [2015/06/18 02:13] – 作成 matsui | 11_php:05_class:02_db_singleton [2015/11/06 07:32] (現在) – matsui | ||
---|---|---|---|
行 1: | 行 1: | ||
+ | ====== 02 DB接続(Singleton) ====== | ||
+ | ===== DB接続Class ===== | ||
+ | |||
+ | <code php> | ||
+ | <?php | ||
+ | |||
+ | class Database | ||
+ | { | ||
+ | | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ); | ||
+ | |||
+ | static $_instance; | ||
+ | private function __construct() { | ||
+ | try{ | ||
+ | // | ||
+ | $dsn_basic = ' | ||
+ | $this-> | ||
+ | $this-> | ||
+ | }catch(Exception $e){ | ||
+ | echo static:: | ||
+ | exit; | ||
+ | } | ||
+ | } | ||
+ | private function __clone(){} | ||
+ | |||
+ | public static function getDb() { | ||
+ | if (!(self:: | ||
+ | self:: | ||
+ | } | ||
+ | //return self:: | ||
+ | return self:: | ||
+ | } | ||
+ | | ||
+ | public function query($sql) { | ||
+ | return query($this-> | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | ===== 呼び出し側 ===== | ||
+ | |||
+ | <code php> | ||
+ | <?php | ||
+ | require_once(' | ||
+ | Database:: | ||
+ | $dbh = Database:: | ||
+ | |||
+ | </ | ||
+ | |||
+ | |||
+ | ===== PHP 5.3未満の場合 ===== | ||
+ | |||
+ | static, self が利用できないので、クラス名をそのまま書く必要があります。 | ||
+ | 5.1, 5.3 の両環境で利用する場合は、下記のように書いておくと両方で利用する事ができます。 | ||
+ | |||
+ | < | ||
+ | <?php | ||
+ | |||
+ | class Database | ||
+ | { | ||
+ | | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ' | ||
+ | ); | ||
+ | |||
+ | static $_instance; | ||
+ | private function __construct() { | ||
+ | try{ | ||
+ | // | ||
+ | $dsn_basic = ' | ||
+ | $this-> | ||
+ | $this-> | ||
+ | }catch(Exception $e){ | ||
+ | echo Database:: | ||
+ | exit; | ||
+ | } | ||
+ | } | ||
+ | private function __clone(){} | ||
+ | |||
+ | public static function getDb() { | ||
+ | if (!(Database:: | ||
+ | Database:: | ||
+ | } | ||
+ | //return Database:: | ||
+ | return Database:: | ||
+ | } | ||
+ | | ||
+ | public function query($sql) { | ||
+ | return query($this-> | ||
+ | } | ||
+ | } | ||
+ | </ |