views:

82

answers:

1

Hi, I need a function with variable number of arguments, to access to the elements of a multidimensional array. I have done in this way ($this->_config is the array)...

function item()
{
    if(func_num_args() != 0){
        $config = $this->_config;
        $args = func_get_args();
        foreach($args as $item){
            $config = $config[$item];
        }
        unset($args);
        return $config;
    }
    else throw new Exception('An item index is required.');
}

Is there a way to do better? Thanks to all!

+1  A: 

In your question you say you have a multidimensional array, so I take it is like this:

$config = array('foo' => array('bar' => array('baz' => 3)));

Calling item('foo', 'bar', 'baz') would run all the way through to the last array and return 3. If that is what you want, you could just write $config['foo']['bar']['baz'] or place your configs in an ArrayObject and use either the array access notation or $config->foo->bar->baz (though all nested arrays must be ArrayObjects too then).

If you want to keep the function, you should add some checking on the index before you grab it, because PHP will raise a Notice about undefined indexes. In addition, why not use InvalidArgumentException instead of Exception. Fits better for this case.

edit: removed some portion of the answer, because it was more like loud thinking

edit after comments
Tbh, I find it a rather awkward approach to reinvent array access through a method like this. In my opinion you should either pass the entire config or a subset to your objects during construction and let them take whatever they need through the regular array accessors. This will decouple your objects from your configManager and allows for easier modification at a later point.

Gordon
the method is inside a class that manages various configuration items, stored in an array ($this->_config). The class load more configuration files in witch ther is an array named $config, and add oll items from all files into $this->_config. Now, it's possible create, in the config file "config_file.php" an array $config with this elements:$config['config_file']['element1'] = 'aaa';$config['config_file']['element2'] = 'aaa';$config['config_file']['database']['user'] = 'user';So, calling in another class... $configmanager->item('config_file', 'database', 'user'), it must return 'user'.
flux
In practice, I don't know how many arguments are passed... thank you for your suggestions, the second one could be useful for me in alternative
flux
ok, you're right... I think I'll do in this way, whatever there is in the array $this->config, it returns the content, also if ther is another array. Thank you very much for your help
flux