As everyone already said, you have to use the keyword global
to avoid mixing with local variables:
function my_func() {
global $db;
...
}
If you really need a global variable, one possible way is to use the $_GLOBALS
:
$_GLOBALS['db'] = $db;
function my_func() {
$_GLOBALS['db']->...;
...
}
It's better to use OOP, but sometimes, a developer needs to write a quick script that do stuff, and PHP is a good choice for this. If you don't want to go OOP-way and still want to use global variables in many functions, here's a workaround.
1- Create a file, let's call it my_globals.php that has this content:
// my so many globals stay here
global $db;
global $a;
global $b;
...
2- In your main file, you would do something like this:
$db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$a = ...;
$b = ...;
function abc(){
include 'my_globals.php';// this will be equivalent as typing all your global variables
...
}
function xyz(){
include 'my_globals.php';// this will be equivalent as typing all your global variables
...
}