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:
Sometimes I see people explicitly passing it as a parameter in the construction or another function call:Code:class Something { public function doAQuery(){ global $database; $database->query(); } } $database = setupDatabase(); $st = new Something(); $st->doAQuery();
(There's singletons as well, but I'm not thinking about that right now)Code: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();
Any advantage of one over the other?



Reply With Quote
Bookmarks