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;
	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?

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

Check: http://php.net/manual/en/language.oop5.static.php

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: http://www.sitepoint.com/forums/showthread.php?t=733507

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.