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.. Link to comment https://forums.phpfreaks.com/topic/197576-connect-to-database-using-class-and-singleton-patter/ 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... Link to comment https://forums.phpfreaks.com/topic/197576-connect-to-database-using-class-and-singleton-patter/#findComment-1037033 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.. Link to comment https://forums.phpfreaks.com/topic/197576-connect-to-database-using-class-and-singleton-patter/#findComment-1037043 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. Link to comment https://forums.phpfreaks.com/topic/197576-connect-to-database-using-class-and-singleton-patter/#findComment-1037052 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.