Answer the question
In order to leave comments, you need to log in
How to bypass global in this situation?
there is a Database.php class, and there is a config.php file.
Actually, when in Database.php I do require(__DIR__ . '/config.php');
and I want to use a variable with config.php in construct, until I enter global $db_name; I won't be able to use them.
Because I know that globals are evil, and I want to keep the code clean from the beginning, I need to find a bypass for this case.
So, what is the workaround in this situation?
Now it looks like this
public function __construct()
{
try {
global $config;
$this->pdo = new PDO("mysql:host=localhost;dbname=" . $config['db_name'], $config['db_user'], $config['db_password']);
} catch(Exception $e) {
echo 'Sorry ' . $e->getMessage();
}
}
Answer the question
In order to leave comments, you need to log in
If you have a goal, besides “make this code work” , there are other goals: to study and do it right ,
I advise you to look towards the introduction of a DI container, including for configs.
This is described in detail in Eliseev’s video, link to an excerpt:
PSR-7 framework 4/6: Dependency injection container
Or take a ready-made DI component (for example, from Symfony)
Pass connection parameters to constructor when instantiating
class Database
{
public function __construct($db_name, $db_user, $db_password)
{
try {
$this->pdo = new PDO("mysql:host=localhost;dbname=" . $db_name, $db_user, $db_password);
} catch (Exception $e) {
echo 'Sorry ' . $e->getMessage();
}
}
}
...........................
$db = new Database($config['db_name'], $config['db_user'], $config['db_password']);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question