PHP通过名称和连接获取变量
问题描述:
我遇到这个问题,通过名称获取变量。我正在做的是包括一个连接路径,我希望连接以某种方式命名。我想遍历这些条件并将它们添加到队列中,但问题是,我无法使用'。'。连接一个变量。PHP通过名称和连接获取变量
代码看起来像这样。配置文件:
//Set the host the databse will connect too
$config_db_hostname='xxx.xxx.xxx';
//Set the user who is connecting to the database
$config_db_user='a user';
//Set the password for user who is connecting to the database
$config_db_pass='abc123';
//Set the database type
$config_db_type='mysql';
//Set the name of the database
$config_db_name='phonephare_development';
//Optional: Set the schema, if any
$config_db_schema='';
//Optional: Set the port, otherwise default port will be used
$config_db_port='';
//Set the prefix for the table names
$config_db_prefix='pf_';
//Set the host the databse will connect too
$config_db_hostname_1='localhost';
//Set the user who is connecting to the database
$config_db_user_1='test';
//Set the password for user who is connecting to the database
$config_db_pass_1='test';
//Set the database type
$config_db_type_1='mysql';
//Set the name of the database
$config_db_name_1='test_development';
//Optional: Set the schema, if any
$config_db_schema_1='';
//Optional: Set the port, otherwise default port will be used
$config_db_port_1='';
//Set the prefix for the table names
$config_db_prefix_1='pv_';
函数获取值:
public static function init(){
if(file_exists(PV_DB_CONFIG)){
include(PV_DB_CONFIG);
for ($i = 0; $i <= 3; $i++) {
if($i){
$profile_id='_'.$i;
} else {
$profile_id='';
}
// Database variables
self::$connections['connection'.$profile_id]['dbhost'] = ($config_db_hostname.$profile_id);
self::$connections['connection'.$profile_id]['dbuser'] = $config_db_user.$profile_id;
self::$connections['connection'.$profile_id]['dbpass'] = $config_db_pass.$profile_id;
self::$connections['connection'.$profile_id]['dbtype'] = $config_db_type.$profile_id;
self::$connections['connection'.$profile_id]['dbname'] = $config_db_name.$profile_id;
self::$connections['connection'.$profile_id]['dbport'] = $config_db_port.$profile_id;
self::$connections['connection_'.$profile_id]['dbschema'] = $config_db_schema.$profile_id;
self::$connections['connection_'.$profile_id]['dbprefix'] = $config_db_prefix.$profile_id;
}
}
}//end init
所以,我怎么能动态地看这个变量?
答
这样你可以阅读“动态”的变量:
$varname = 'config_db_user';
if ($i)
$varname .= '_' . $i;
$varvalue = $$varname; // $varvalue contains the value now.
但是,这将使你的代码真的难以阅读,难以维持。而是让你的配置是这样的:
$profiles[1]['config_db_user'] = 'whatever';
然后,你可以阅读$profiles[$profile_id]['configfield]
得到你想要的东西。可能还有其他更好的方法,但不要把动态变量名放在一起,因为这是最糟糕的。
答
以不同的方式构建您的数据。你想迭代低谷组变量共享一个相似的名字..但是,它没有发生你的配置选项使用数组,并迭代低谷呢?
男人,停止这样做。改用数组! – GolezTrol