Hi.
What I usually did was to create an instance of my database class and pass it into the classes that need it. (usually via the constructor).
This way there is only one instance of the class in play.
Another method I have used in the past was to have the class
extend my database class, which would allow me to use the database class as a part of the current class.
This is obviously not a good idea if you use lots of objects in your code, but can be made to work well in smaller projects.
Then you could always use a static approach, creating a static class that could be used everywhere without actually creating an object instance to pass around.
This is probably the simplest way, but for some reason not that appealing. (Kind of feels like abusing the global scope :P)
A compromise between the two could be to create a static class that creates or returns an existing database object. That way you would only have a single instance of your object in play, without having to pass it around. It could simply be fetched wherever it is needed.
Somewhat like:
-
class MyDatabase {
-
private static $_link;
-
public static function GetConnection(){
-
if(self::$_link == null){
-
self::$_link = new mysqli("host", "usr", "paswd", "db");
-
if(mysqli_connect_errno()) {
-
throw new Exception("Database connection failed: ". mysqli_connect_error());
-
}
-
}
-
return self::$_link;
-
}
-
}
-
-
class foo {
-
public function DoSomething(){
-
$dbLink = MyDatabase::GetConnection();
-
$result = $dbLink->query("SHOW TABLES");
-
if($result) {
-
while($row = $result->fetch_array()) {
-
echo " - " . $row[0] ."<br />";
-
}
-
}
-
$result->close();
-
}
-
}
-
This is my favorite at the moment :)