我正在构建一个类,以便方便地从另一个 php 文件中获取变量。
问题是我使用双美元符号来创建 $variable_name => $$varible_real_value 样式的哈希图,并且我希望所有迭代器属性都是类变量。在 __constructor 范围内定义新变量可能会覆盖文件中的变量。有问题的代码是
foreach($this->args AS $this->iterator) {
$this->data->$this->iterator = $$this->iterator;
}
但是当我用
foreach($this->args AS $var) {
$this->data->$var = $$var;
}
变量“$var”将被覆盖。
class DataFile {
private
$data = null,
$iterator = null,
$args = null
;
public function __construct($file) {
require($file);
unset($file);
$this->args = func_get_args();
array_shift($this->args);
$this->data = new ArrayObject();
foreach($this->args AS $this->iterator) {
$this->data->$this->iterator = $$this->iterator;
}
}
public function __get($key) {
return $this->data->$key;
}
}
示例用法:
$conf = new DataFile('mysql.php', 'var');
$databaseName = $conf->var->database;
有什么解决方法吗,
谢谢