This is what most of my database-related library code looks like:
lib.php
<?php
$dbh = new PDO(...);
function doSomeDatabaseThing() {
global $dbh;
return $dbh->doStuff();
}
function doSomeOtherThing() {
global $dbh;
return $dbh->doSomeOtherStuff();
}
index.php
<html>
<head>...</head>
<body>
<?php
require_once('lib.php');
echo doSomeDatabaseThing();
?>
</body>
</html>
I keep reading that globals in PHP are generally bad. Of course, this doesn't mean that I should never use globals, but it seems wrong to repeatedly use this pattern in almost all database code I write.
So, how should I do this without globals? I could try something like
lib.php
$dbh = new PDO(...);
function doSomeDatabaseThing($dbh) { ... }
index.php
doSomeDatebaseThing($dbh);
but it looks ugly to have to write "($dbh)
" every single time I call a database function.
Is there a better way to solve this?