I have a functions.php file that has one PDO Connection i use to access the database and all that good stuff it's this one:
$host = "localhost";
$db = "maindatabase";
$adminuser = "admin";
$adminpw = "123456";
global $connection;
$connection = new Connection($host,$adminuser,$adminpw,$db);
And i require this script on every file that needs to access to the database, the thing is in some cases i want to change from $db = "maindatabase"; to $db = "anotherdb"; and i know i can do it with just a setter
$connection->setDatabase("anotherdb");
But since i require the functions.php file into every other file i don't know if it will overwrite itself back to default, does anybody knows how can i change it and make it stay ?
EDIT
I have changed require to require_once in my code and since the PHP Documentation says if the file has already been required it will not add it again, do you think this will solve the issue ?
解决方案
This is the classic problem with global variables. Your program state is unpredictable. You can't know which database you're referring to.
Your solution is proper dependency injection.
Implement a factory class to generate the correct database connection on demand, and don't use global variables. That's the correct solution.