在函数中使用数据库对象

In a webapp I am building I make use of a PDO database object for querying my database. This is instantiated at the top of every page using a custom class that I built based on PDO:

$db = new database; //database is the name of my class.

I then use the class like so in my script:

$db->query("SELECT field FROM table");
$results = $db->resultset();

I have a number of standalone functions that need to make use of the database object.

My question is is it better practise to pass the $db to the function as an argument or just globalize from within the function, given $db is a globally used variable. However I have heard things about avoiding polluting the global namespace.

i.e.

function myFunction($db, $a1, $a2){
    //stuff
}

vs

function myFunction($a1, $a2){
    global $db;
    //stuff
}

In my opinion, global vars are rarely a good practice. I think you should use the first solution: passing the db instance as first parameters to your function.

IF you only have one instance of your database, an even better option would be to make your database class a singleton. This would allow you to do something like $db = database.getInstance(); in your functions.