Your problem has multiple solutions.
The first is obvious: declare your DB object globally (global $DB; $DB = new DB();), which will allow you to use the following: global $DB; $DB->connect(); or otherwise.
The other solution is a design pattern called the singleton pattern. It works stupidly well but has a few drawbacks. I’ll write a tutorial on design patterns soon, so if you want to know more, stay tuned. This specific one is characterised by three properties:
- Its constructor is private. This prevents the class from being instantiated from outside itself
- There can only be one instance of the class
- It is located using either a directory locator, Inversion of Control or through knowing the exact class name (bad)
The pattern is pretty simple and summarized to this:
[php]<?php
class MySingleton {
private static $instance;
private function __construct() {
// Your constructor
}
public static function getInstance() {
if (!isset(static::$instance)) {
static::$instance = new self();
}
return static::$instance;
}
}[/php]
What you then do is, instead of using the keyword new to create an instance, you call getInstance(). If it is the first time you call it, it will initialize an instance. Otherwise, it will return it.
This is particularly potent for database connections, as it allows you to easily keep one connection running.