I made a config.php file which contains MySQL connection info.

$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('Cannnot connect!');
        mysql_select_db(DB_NAME, $con) or die(mysql_error());

My question is how do I add it into a class?

<?php
require_once('config.php');

class users {
	
	private $id;
	
	public function __construct($id) {
		
		global $con;
$sql = "MySQL script'";
        $rs = mysql_query($sql) or die(mysql_error());
}
}
mysql_close($con);

This does not work, I know that I can make it like this:

private $id;
private $con;
public function __construct($id) {
$this->con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('Cannnot connect!');
        mysql_select_db(DB_NAME, $con) or die(mysql_error());
}.......

to make it work, but then config.php will be useless in this situation.
How to I global the variables from config.php in class?

Thanks.

Recommended Answers

All 4 Replies

For starters a configuration file should only contain configuration values.
If you're working with OOP move the database initialization to some sort of database class.

In my opinion there are two approaches to this. You could make your database connection into a class and use the singleton pattern. Basically this pattern stores an instance of itself in itself. If it already has an instance it returns it, if not it creates a new database object, stores it and then returns it.

<?php
/**
 * Establishes a database connection and utilizes a singleton pattern
 * implementation to ensure only one instance exists during execution
 */
class Database
{
	/**
	 * Stores an instance of the database class
	 * @var Database
	 */
	private static $__instance;
	
	/**
	 * Setups the database
	 * Can only be called from within this class
	 */
	private function __construct(){
		//Read in configuration file
		//Establish database connection
		//Store connection in this object
		//etc etc		
	}
	
	/**
	 * Returns a new instance of the Database class OR
	 * returns the instance stored in the static variable
	 * 
	 * @return Database
	 */
	public static function getInstance(){
		if( !self::$__instance ){
			self::$__instance = new Database();
		}
		return self::$__instance;
	}
}

In your code you would use it like this:

<?php
class Users
{
	public function dbTask(){
		$db = Database::getInstance();
		//$db->query() or something
	}
}

This is probably the easiest and most straightforward method to establish a single database connection for the entire execution of your application. However, it also creates a hard dependency on the Database class within any class you use it.

The alternative to this is would be to use dependency injection. Loosely all this means is passing the dependent classes into an object. For example:

<?php
class Users
{
	protected $_db;
	
	public function __construct( Database $db ){
		$this->_db = $db;
	}
	public function dbTask(){
		//$this->_db->query() <-- or something
	}
}

Usage:

<?php
$db = new Database(); //Assuming Database is no longer a singleton implementation
$user = new User($db); //User object requires the $db variable to be a Database instance

The first method is simple and well established, but it creates hard dependencies and is very difficult to test. But, that is beyond the scope of this response.

The second method is still simple, on a small scale, but it creates no dependencies on external classes. It provides a lot of benefits such as being able to mock objects for testing, again out of the scope. Dependency injection will take your coding to a whole other level. If DI is of interest I highly suggest you look at the slideshare link.

Check out some of these for more in-depth information on the two topics.

Dependency Injection
http://www.slideshare.net/fabpot/dependency-injection-with-php-and-php-53
http://www.potstuck.com/2009/01/08/php-dependency-injection/

Singleton Pattern
http://en.wikipedia.org/wiki/Singleton_pattern
http://www.fluffycat.com/PHP-Design-Patterns/Singleton/
http://www.ibm.com/developerworks/library/os-php-designptrns/

class databaseaction
{
    private $db_host;
    private $db_user;
    private $db_passwd;

    public funciton dbconnect($dbhost, $dbuser, $dbpasswd)
    {
        $this->db_host = $dbhost;
        $this->db_user = $dbuser;
        %this->db_passwd = $dbpasswd;
        mysql_conncet($this->db_host, $this->db_user, $this_passwd) or die (mysql_error());
    }

// other function 

}

i long time no write php script. maybe some syntax is error, but the logic is right.

mschroeder have nailed everything IMHO.

class databaseaction
{
    private $db_host;
    private $db_user;
    private $db_passwd;

    public funciton dbconnect($dbhost, $dbuser, $dbpasswd)
    {
        $this->db_host = $dbhost;
        $this->db_user = $dbuser;
        %this->db_passwd = $dbpasswd;
        mysql_conncet($this->db_host, $this->db_user, $this_passwd) or die (mysql_error());
    }

// other function 

}

i long time no write php script. maybe some syntax is error, but the logic is right.

I cannot see syntax error except a typo (which will introduce a syntax error of course)

public funciton dbconnect($dbhost, $dbuser, $dbpasswd)

should be

public function dbconnect($dbhost, $dbuser, $dbpasswd)

yes, it's a wrong word
My fingers play faster

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.