天天看點

mysql 單态設計模式_PHP設計模式-Singleton 單例(單元素)模式

整理一下自己的學習Aaron Saray 寫的PHP設計模式一些demo和自己的了解。大佬看完如果發現鄙人了解有誤請立即指出,感謝拍磚,跪求鞭打

class Singleton

{

private static $_instance = NULL ;

private $_pdo = NULL ;

private function __clone(){}

private function __construct(){

try{

$this->pdo =new \PDO("mysql:dbname=資料庫名字;host=127.0.0.1,root,123456");

$this->pdo->exec('SET NAMES utf8');//設定通信編碼

$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

}catch(PDOException $e){

die('error:'.$e->getMessage());

}

}

public static function getInstance(){

// 檢測其并不是本類執行個體

if( !self::$_instance instanceof self ){

self::$_instance = new self;

}

return self::$_instance;

}

public function select($dbname,$filed,$where)

{

$stmt = self::$_pdo ->prepare(" SELECT {$filed} FROM {$dbname} {$where}");

$stmt->execute();

return $stmt->fetchAll(PDO::FETCH_ASSOC);

}

}

Singleton::getInstance();