2012-04-11 85 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)。