several ways:
1) include the DB connection script at the beginning of the class you're using it in.
PHP Code:
<?php
class needsDatabase{
var $DBconn;
function __construct(){
include('db_conn.php');
// this script would assign the connection to some variable, say $db,
// which you could then use in the class
$this->DBconn = $db;
}
// rest of class
}
?>
2) pass the connection into the object when you create it:
PHP Code:
<?php
include('db_conn.php'); // this gives you your connection ( $db )
new needsDatabase($db);
class needsDatabase{
var $DBconn;
function __construct($DBconn){
$this->DBconn = $DBconn;
}
// rest of class
}
?>
3)you could connect to the database at the beginning of your script and then declare the $db variable as global inside the class:
PHP Code:
<?php
include('db_conn.php'); // this gives you your connection ( $db )
class needsDatabase{
var $DBconn;
function __construct(){
$this->DBconn = $GLOBALS['db'];
}
// rest of class
}
?>
number 2 is straightforward, but a little tedious in that you have to pass the variable that holds the connection each time. number 3 is the method I generally use, even though you have to make sure all of your classes refer to the correct global-scope variable (I just use the same variable name all the time). More about $GLOBALS
Bookmarks