使用PDO选择多个数据库 [英] Select multiple databases with PDO

查看:207
本文介绍了使用PDO选择多个数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个functions.php文件,该文件具有一个PDO连接,我用它来访问数据库,而所有这些好东西就是这个:

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);

然后我require在需要访问数据库的每个文件上使用此脚本,在某些情况下,我想将其从$db = "maindatabase";更改为$db = "anotherdb";,我知道我可以用设置器来完成

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");

但是由于我requirefunctions.php文件转换为其他文件,所以我不知道它是否会将其覆盖为默认值,所以有人知道如何更改并使其保留吗?

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 ?

编辑

我已在代码中将require更改为require_once,并且由于PHP文档指出如果需要该文件,它将不再添加它,您认为这样可以解决问题?

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.

这篇关于使用PDO选择多个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆