php——資料庫連接的偽單例模式代碼

來源:互聯網
上載者:User
各位redis群的同學,幫忙查看指正一下代碼,多謝了,希望看到各位的改進意見
<?phpclass Singleton{// MYSQL資料庫連接資訊const MYSQLHOSTNAME = "127.0.0.1";const MYSQLCHARSET = "utf8";private static $instances = array(); //偽類單例private $db; //資料庫連接控制代碼/** * Description:私人化建構函式,防止外界執行個體化對象 */private function __construct($dbname, $username, $password){//串連資料庫$this->db = new mysqli(self::MYSQLHOSTNAME, $username, $password, $dbname);$this->db->set_charset(self::MYSQLCHARSET);if (mysqli_connect_errno()){throw new CircleMysqlException("error", 1000);}}/** * Description:私人化複製函數,防止外界複製對象 */private function __clone(){}/** * Description:靜態方法,單例訪問統一入口 * @return Singleton:返回應用中的唯一對象執行個體 */public static function GetInstance($dbname, $username, $password){$hash = (string) $dbname;if (!isset(self::$instances[$hash])){self::$instances[$hash] = new self($dbname, $username, $password);}return self::$instances[$hash];}/** * Description:擷取資料庫的私人方法的串連控制代碼 */public function GetDbConnect(){return $this->db;}/** * Description:關閉資料庫連結的方法 */public function CloseDbConnect($dbname){$hash = (string) $dbname;self::$instances[$hash]->db->close();unset(self::$instances[$hash]);}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.