如何创建全局配置文件? [英] How to create global configuration file?
问题描述
是否可以使用在类内部可见的全局变量来创建配置文件?与此类似:
Is there any possibility to create a configuration file with global variables that are visible inside the class? Something similar to this:
config.php:
config.php:
$config['host_address'] = 'localhost';
$config['username '] = 'root';
$config['password'] = 'root';
$config['name'] = 'data';
db.php:
include('config.php');
class DB
{
private $_config = array($config['host_address'], $config['username'], $config['password'], $config['name']);
...
当前属性:
private $ _config = array();
我不想通过构造函数传输到我的Singleton数据库连接器:
I don't want to transmit through the constructor to my Singleton database connector:
DB::getInstance(array('localhost', 'root', 'root', 'data'));
推荐答案
您的问题是您试图在此处的类定义中使用表达式:
Your problem is that you are trying to use an expression in the class definition here:
class DB
{
private $_config = array($config['host_address'], ...
从语法上讲这是不正确的(您只能使用恒定值),而且我不希望它在此处定位预期的范围.相反,您应该做的是在构造函数中初始化此属性:
That is syntactically incorrect (you can only use constant values for that), and I wouldn't expect it to locate the intended scope there. What you should do instead is initialize this property in the construtor instead:
class DB
{
private $_config;
function __construct() {
global $config;
$this->_config = array($config['host_address'], $config['username'], $config['password'], $config['name']);
}
甚至更懒惰,只需使用include('config.php');
代替global $config
别名即可.这样,您的配置脚本将在构造函数中将$ config提取为局部变量,这就是您所需要的.
Or even lazier, just use include('config.php');
in place of the global $config
alias. That way your config script will extract $config as local variable within the constructor, which is all you need.
这篇关于如何创建全局配置文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!