Question

I want to access an assoc array by using a delimited string.

Configuration::get('enviroment/database/default');

Below is what I have, and works, but it's far from perfect.

public static function get($key) {
    $array = explode('/', $key);
    switch(count($array)) {
        case 1:
            $value = self::$cfg[$array[0]];
            break;
        case 2:
            $value = self::$cfg[$array[0]][$array[1]];
            break;
        case 3:
            $value = self::$cfg[$array[0]][$array[1]][$array[2]];
            break;
    }
    return $value;
}

How can I clean up this function and remove the hardcoded 'depth' limit?

Était-ce utile?

La solution

public static function get($path) {
    $result = self::$cfg;

    foreach (explode('/', $path) as $key) {
        if (!array_key_exists($key, $result)) {
            throw new InvalidArgumentException("Path $path is invalid");
        }
        $result = $result[$key];
    }

    return $result;
}

BTW, using a static class is not usually a good idea, you should instantiate it. See How Not To Kill Your Testability Using Statics.

Autres conseils

You can just use a foreach() loop, and then assign that value to the key of a variable that will hold self::$cfg:

$confArr = self::$cfg;

foreach(explode('/', $key) as $cfg)
{
    $confArr = $confArr[$cfg];
}

return $confArr;

It might be wise to add in some error checking to make the key exists within self::$cfg, mind you.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top