Passing database handle to function vs global

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:


class Something
{
	public function doAQuery(){
		global $database;
		$database->query();
	}

}
$database = setupDatabase();
$st = new Something();
$st->doAQuery();

Sometimes I see people explicitly passing it as a parameter in the construction or another function call:


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();

(There’s singletons as well, but I’m not thinking about that right now)

Any advantage of one over the other?

The first one is more the old school way of doing it before we had good OOP in php. But more than that global vars are ugly, bad practice in most cases, And could lead to potential insecure code.

The second method is considered best practice, It is using dependency injection, is simply written, much more secure & controllable. Also allows the application to scale in a much cleaner and more effective.

But both have a time and place. Database code fits better with the second option.