I have the following code that makes a PDO object, which is at the end of core.php:
try {
$dbh = new PDO("mysql:host=localhost;dbname=xxx", 'xxx', 'xxx');
} catch (PDOException $exc) {
header(HTTP_500_HEADER);
die('Database connection failure');
}
In index.php, which is in a directory above it, it includes fine and I am able to access it. I am not accessing $dbh from a function.
However, when I try to access it from inside a function like this (this time it’s a different file in a different dir):
require_once '../_/core.php';
var_dump($dbh);
$show_html = true;
$rm = $_SERVER['REQUEST_METHOD'];
function login_check() {
var_dump($dbh);
}
The first var dump shows it is a PDO object, but the second shows it’s null.
If you want to access a global variable in a function you need to define it (here
$dbh) as global inside the function (also see the manual):