I have a database class, which is used to make select, update, delete MySQL queries.
Now, I want to create a MySQL query inside another class, but if I define $db = new DB();
in index.php
, I can't use the $db
var in another class. Do I have to define the variable $db
over and over again, if I want to make a query? Or is there a way to make the $db
var with an object global var?
You probably want a singleton. This gives you a way to get an instance of DB anywhere in the code. Then anywhere you want to do a query, first do
$db = DB::getInstance();
.An alternative is dependency injection, which passes a DB instance to all classes which need one.
Use the magic function
__autoload()
.First make your database class a singleton. And then in your new class you can do something like:
You might define it as global in your index.php file, and in the class constructor also put
$this->db &= $GLOBALS['db'];
The cleanest approach would be to aggregate the database class where needed by injecting it. All other approaches, like using the
global
keyword or usingstatic
methods, let alone a Singleton, is introducing tight coupling between your classes and the global scope which makes the application harder to test and maintain. Just doand
Use Constructor Injection if the dependency is required to create a valid state for the instance. If the dependency is optional or needs to be interchangeable at runtime, use Setter Injection, e.g.
In your
index.php
file useYou may also use
include_once
, which will give you a warning instead of an error if the 'path_to_file_with_class.php' file is not available.