开发者

text1/text2 to array['text1']['text2']?

开发者 https://www.devze.com 2023-02-12 11:01 出处:网络
I\'m trying to make something like function config( $string ){ require \'configuration.php\'; return $config[$string];

I'm trying to make something like

function config( $string ){
    require 'configuration.php';
    return $config[$string];
}

but i have a problem when my config has a 2D array. like:

$config['features'] = array(
        'memcached' => T开发者_如何转开发RUE,
        'compress'  => TRUE,
        'gzip'      => TRUE
);

how can i get config('features/memcached') or if can we have three or more threaded array like config('features/memcached/version14/etc') ( example ) to return true but still works when we do something like config('features') returns the array just like the function above. any ideas ?


Just split the string into keys:

function config( $string ){
    require 'configuration.php';
    $keys = explode('/',$string);
    $return = $config;
    foreach($keys as $key){
        $return = $return[$key];
    }
    return $return;
}

Here you can do this too:

config('features/others/foo/bar');

if this exists:

$config['features'] = array(
    'memcached' => TRUE,
    'others'  => array( 'foo' => array( 'bar' => 42 ) )
);


function config( $string ){
    require 'configuration.php';
    $p = explode("/",$string);
    $r =  $config;
    foreach($p as $param)
        $r = $r[$param];
    return $r;
}


you could try this (written from head, not tested):

function config( $key, $subkey = null ){

    require 'configuration.php';

    return ($subkey)? $config[$key][$subkey] : $config[$key];

}

use it as config('features','memcached') and note that this will only work with one level of sub-arrays. if there could be more or if you want to stick to the config('features/memcached')-syntax, you could try something like this (same as the function above - this isn't tested, maybe you'll have to fix a bug on your own ;) ):

function config( $string ){

    require 'configuration.php';

    $keys = explode('/',$string);

    foreach($keys as $key){
        $config = $config[$key];
    }

    return $config;

}


You can use that aproach:

public function config($path = null, $separator = '.')
{
    if (!$path) {
        return self::$_constants;
    }

    $keys = explode($separator, $path);
    require 'configuration.php';
    $value = $config;
    foreach ($keys as $key) {
        if (!isset($value[$key])) {
            throw new Exception("Value for path $path doesn't exists or it's null");
        }
        $value = $value[$key];
    }
    return $value;
}

In your example calling config('features') will return array, and config('features.compres') will return true and so on.

0

精彩评论

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