It seems like common practice to set up a database connection handle at the start of a script, and call it as a global within functions:
class Something
{
public function doAQuery(){
global $database;
$database->query();
}
}
$database = setupDatabase();
$st = new Something();
$st->doAQuery();
Sometimes I see people explicitly passing it as a parameter in the construction or another function call:
class Something
{
private $database;
public function __construct(Database $database){
$this->database=$database;
}
public function doAQuery()
{
$this->database->query();
}
}
$database = setupDatabase();
$st = new Something($database);
$st->doAQuery();
(There’s singletons as well, but I’m not thinking about that right now)
Any advantage of one over the other?