Jump to content

Connect to database using Class and singleton patter..


Scooby08

Recommended Posts

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..

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... :confused:

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.