我有这个问题得到一个变量的名称。我所做的是包括一个路径与连接,我希望以某种方式命名的连接。我想遍历这些连接并将它们添加到队列中,但问题是,我不能使用''来连接一个变量
代码是这样的。配置文件:
//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]
来得到你想要的。可能还有其他更好的方法,但是不要把动态变量名放在一起,因为那是最糟糕的。
检查PHP变量。
注意:这是一个糟糕的配置文件格式开始,你真的应该把单独的连接到不同的数组。查看phpmyadmin的配置文件
用另一种方式构造数据。您希望遍历一组具有相似名称的变量。然而,它没有想到你使用数组配置选项和迭代?