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

Link to comment
Share on other sites

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:

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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