Code: Select all
// Create DB object
$db = new DB();
// Here I can use the global variable
$db->query("SELECT * FROM table");
// But inside a function or a class method
function my_function() {
// Here $db is obviously not visible! :(
} http://www.ultramegatech.com/blog/2009/ ... n-pattern/
I have made a similar thing:
Code: Select all
class DB() {
private static $last_db = null;
public function __construct() {
// mysql_connect(); etc...
self::$last_db = $this; // store last object created
}
public static function get() {
if (is_null(self::$last_db)) throw new Exception('DB: no database opened');
return self::$last_db;
}
}
// And now in my functions I can do
function my_function() {
$db = DB::get();
$db->query("SELECT * FROM table");
}Thank you all...