1

I am trying to write a db util class using the singleton pattern. My problem is that the "connection" object is always null. The connection settings are correct. What could i be doing wrong ? Also, i am relatively new to php development. What method should i use to figure out what's wrong ? Code follows.

 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; } } 
1
  • Well actually, the singleton pattern looks too complicated to you, but that's not a problem at all: Just don't use singletons. You don't need them in PHP. In your case you only need a global variable for the database connection. - But if you feel like copy and paste, the PHP manual has a code example for the Singleton Pattern (not that this makes anything better, don't use it ). Who needs singletons?. Commented Apr 11, 2012 at 14:27

4 Answers 4

3

Your constructor function should be named __construct (notice two underscores).

Also, in your constructor, you have one parameter, $conn. When you call new DBUtil(), you are not providing that input parameter, so perhaps it's calling the default contructor, not your custom one.

If you want the input parameter $conn to be optional, try __construct($conn = null).

Or try calling it as new DBUtil(null).

Sign up to request clarification or add additional context in comments.

Comments

2
private function _constructor($conn) ?? 

should this be

private function __construct($conn) 

1 Comment

Also might want to set the default value to null, as your not passing a $conn variable when instantiating the object. private function __construct($conn = null)
2

There should be two underscores __ (__construct).

Comments

-1

You should do like this :

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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.