模仿網友寫的一個單例模式實現的資料庫連接,在建構函式中,成功執行個體化了,並把執行個體化的mysqli賦值給了$_instance
但是在下面的函數getInstance中,擷取到的值,卻是$db_config
請教大家一下,是哪裡錯了?代碼還有哪些地方需要改進?謝謝!
class DB{ private $db_config = './config.php'; private static $_instance; private function __construct() { if (file_exists($this->db_config)) { require $this->db_config; self::$_instance = new mysqli($db_host, $db_name, $db_passwd); } else { throw new Exception('not found database configuration file.'); } } /** * 單例方法 使用者訪問執行個體的靜態方法 * * @return void */ public function getInstance() { if (self::$_instance == null) { self::$_instance = new self; } file_put_contents('2.txt', var_export(self::$_instance,true), FILE_APPEND); return self::$_instance; } /** * 防止對象被複製 * * @return void */ private function __clone() { trigger_error('Clone is not allow!', E_USER_ERROR); }}
回複內容:
模仿網友寫的一個單例模式實現的資料庫連接,在建構函式中,成功執行個體化了,並把執行個體化的mysqli賦值給了$_instance
但是在下面的函數getInstance中,擷取到的值,卻是$db_config
請教大家一下,是哪裡錯了?代碼還有哪些地方需要改進?謝謝!
class DB{ private $db_config = './config.php'; private static $_instance; private function __construct() { if (file_exists($this->db_config)) { require $this->db_config; self::$_instance = new mysqli($db_host, $db_name, $db_passwd); } else { throw new Exception('not found database configuration file.'); } } /** * 單例方法 使用者訪問執行個體的靜態方法 * * @return void */ public function getInstance() { if (self::$_instance == null) { self::$_instance = new self; } file_put_contents('2.txt', var_export(self::$_instance,true), FILE_APPEND); return self::$_instance; } /** * 防止對象被複製 * * @return void */ private function __clone() { trigger_error('Clone is not allow!', E_USER_ERROR); }}
也是一個渣渣,你可以參考一下這個
http://www.jellybool.com/post/php-database
- 在建構函式裡, 你的代碼已經把
mysqli賦值給 self::$_instance了
getInstance要改成 static
public static function getInstance() { if (self::$_instance == null) { new self; } file_put_contents('2.txt', var_export(self::$_instance,true), FILE_APPEND); return self::$_instance; }
附加一篇鳥哥寫的單例模式文章
http://www.laruence.com/2011/03/18/1909.html