2012-04-11 86 views
1

我正在嘗試使用單例模式編寫db util類。我的問題是,「連接」對象始終爲空。連接設置是正確的。我可能做錯了什麼?另外,我對PHP開發比較陌生。我應該用什麼方法來弄清楚什麼是錯的?代碼如下。mysqli構造函數返回null

class DBUtil { 
     public $connection = NULL; //mysqli_connection object 
     private static $instance = NULL; 

     private function _constructor($conn){ 
      //$this->connection = mysqli_connect(TagMetroConfiguration::getConfigurationValueFor("db_servser_name"), TagMetroConfiguration::getConfigurationValueFor("db_username"), TagMetroConfiguration::getConfigurationValueFor("db_password"), TagMetroConfiguration::getConfigurationValueFor("db_name")); 
      $this->connection = new mysqli("localhost", "root", "toor", "testdb"); 
     } 

     public static function getInstance(){ 
      if(DBUtil::$instance == NULL){ 
       try{ 
        DBUtil::$instance = new DBUtil(); 
       }catch(Exception $ex){ 
        throw new Exception("Unable to create DB Instance"); 
       } 
      } 

      return DBUtil::$instance; 
     } 
} 
+0

其實,單身模式對你來說看起來太複雜了,但這根本不是問題:不要使用單例。你不需要他們在PHP中。在你的情況下,你只需要一個用於數據庫連接的全局變量。 - 但是如果你想複製和粘貼,[PHP手冊有一個單例模式代碼示例](http://php.net/manual/en/language.oop5.patterns.php#language.oop5.patterns。單身)(不是說這樣做會讓事情變得更好,不要使用它)。 [誰需要單身?](http://stackoverflow.com/q/4595964/367456)。 – hakre 2012-04-11 14:27:58

回答

3

你的構造函數應該被命名爲__construct(注意兩個下劃線)。

此外,在您的構造函數中,您有一個參數$conn。當你調用new DBUtil()時,你沒有提供該輸入參數,所以也許它調用了默認的構造函數,而不是你自定義的。

如果要輸入參數$conn爲可選項,請嘗試__construct($conn = null)

或嘗試將其稱爲new DBUtil(null)

2
private function _constructor($conn) ?? 

這應該是

private function __construct($conn) 
+0

也可能希望將默認值設置爲null,因爲在實例化對象時不傳遞$ conn變量。私人函數__construct($ conn = null) – 2012-04-11 14:30:16

-1

你應該這樣做:

class DBUtil { 

     private static $instance; 

     private function _construct(){ 
      $this->$instance = new mysqli("localhost", "root", "toor", "testdb"); 
     } 

     public static function getInstance(){ 
      if(!isset(self::$instance){ 
       try{ 
        self::$instance = new DBUtil(); 
       }catch(Exception $ex){ 
        throw new Exception("Unable to create DB Instance"); 
       } 
      } 

      return self::$instance; 
     } 
2

應該有兩個下劃線____construct)。