Best practice using database function/class

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;
	//run query...

Using the class I’m having to call the global object every time I want to call the function.

global $databasewrapper;

Is this necessary? Am I perhaps missing a much more elegant way? What’s everyone else using?

Jou can make your object Static so you will be able to acces it everywhere (if the code is included in your page somewhere)


You could use a singleton which will allow you to access the same database object everywhere in your code.

There was a similar topic a couple of days ago:

Singletons/static methods (and global variables) all have disadvantages when it comes to maintainability and code re-use. lastcraft explains it here: better than I could.