For something like a database class, I like to use the singleton pattern. Then I can access it from any other object without those objects causing multiples instances of the database class.
Singleton Database class:
<?php
class Database
{
private static $instance;
private function __construct()
{
// do stuff/call methods to set up db connection
}
public static function getInstance()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
// Prevent users to clone the instance
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
// various DB methods would follow here
}
Using it in another class:
require_once 'Database.class.php';
class myClass
{
private $db;
public function __construct()
{
$db = Database::getInstance();
}
public function someMethod()
{
$sql = "SELECT * FROM table";
$result = $this->db->query($sql);
}
}