Search code examples
phpclass-variablesdollar-sign

Accessing object variable via double dollar sign


I'm building a class in order to get variables form another php files conveniently.

Problem is that I'm using double dollar sign in order to get create $variable_name => $$varible_real_value styled hashmap and i want all iterator attributes to be class variables. Defining new variable in __constructor scope might overwrite variables from files. Problematic piece of code is

foreach($this->args AS $this->iterator) {
    $this->data->$this->iterator = $$this->iterator;
}  

But when i replace it with

foreach($this->args AS $var) {
    $this->data->$var = $$var;
}  

Variable '$var' will be overwritten.

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

}

Example usage:

$conf = new DataFile('mysql.php', 'var');
$databaseName = $conf->var->database;

Is there any workaround for this,

Thank you


Solution

  • $this->data->$this->iterator is ambiguous. Do you mean the property of $this->data that has the name of $this->iterator or the iterator property of $this->data->$this?

    You need to make it unambiguous:

    $this->data->{$this->iterator}
    

    The same goes for $$this->iterator.