For ages I’ve been using a simple query() function which connects to the database if a handle isn’t already available, and then runs whatever query is passed to it.
I’ve been going more object orientated lately, and started using a database wrapper class to handle connections, queries and handy utility functions.
The thing is, using the simple function, I didn’t need to worry about scope - I could call it anywhere (within functions, or whatever) and it would create the connection handle and use it.
function mydbconn()
{
global $conn;
//connection stuff
}
function query()
{
global $conn;
if(!$conn)
{
mydbconn();
}
//run query...
}
Using the class I’m having to call the global object every time I want to call the function.
global $databasewrapper;
$databasewrapper->query()
Is this necessary? Am I perhaps missing a much more elegant way? What’s everyone else using?
Singletons/static methods (and global variables) all have disadvantages when it comes to maintainability and code re-use. lastcraft explains it here: http://www.sitepoint.com/forums/showthread.php?t=686549 better than I could.