Scooby08 Posted April 4, 2010 Share Posted April 4, 2010 I'm trying to connect to a database using this code below, which works, but I just have a feeling that it is written incorrectly and was hoping someone could point me in the right direction to sorting this out.. <?php class Database { private static $db; private function __construct(){ mysql_connect(DB_HOST, DB_USER, DB_PASS); mysql_select_db(DB_NAME); } public static function instance(){ if (!self::$db){ self::$db = new Database(); } return self::$db; } } Database::instance(); ?> I seem to think my constructor might be written or used incorrectly.. Could anybody give some suggestions?? What I was originally trying to do was avoid the use of using global connections to the database and from what I've been reading I think this might be the right way to go.. Thanks.. Quote Link to comment Share on other sites More sharing options...
ialsoagree Posted April 5, 2010 Share Posted April 5, 2010 What you're trying to accomplish isn't exactly clear (or perhaps just not to me). If you're trying to get a variable that has the database resource attached to it you can access from anywhere, then your method won't work because you're not saving the database resource to a variable: mysql_connect(DB_HOST, DB_USER, DB_PASS); If you're just trying to create access to the database in the global scope, mysql_connect() does that no matter where it is called, this method is a lot of work when simply calling mysql_connect will do the same thing. Or perhaps I'm missing something... Quote Link to comment Share on other sites More sharing options...
Scooby08 Posted April 5, 2010 Author Share Posted April 5, 2010 Exactly!! Im not doing the second.. I want to call the database throughout the rest of all my files.. Well it doesent even have to be the database.. It is just globals I'm trying to get rid of.. Quote Link to comment Share on other sites More sharing options...
trq Posted April 5, 2010 Share Posted April 5, 2010 It is just globals I'm trying to get rid of.. Singletons aren't much better. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.