开发者

Access to elements of a multidimensional array, with a function

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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜