Xees
Xees

Reputation: 462

Use a function that uses a global array, within the array itself

I have the following code:

$conf = array(
'site'  => array(
    'theme'         => 'master',
    ),
'url'   => array(
    'site'          => 'localhost',
    'up'            => conf('url.site')    . '/uploads',
    'admin'         => conf('url.site')    . '/admin',
    'theme'         => conf('url.site')    . '/theme/' . conf('site.theme'),
    )
);

and the following function:

/**
 * Return a configuration setting from the array.
 * @example
 * GET: conf('url.site')               => $conf['url']['site'] = 'localhost'
 * SET: conf('url.site', '127.0.0.1')  => $conf['url']['site'] = '127.0.0.1'
 *
 * @param  string $path the dot syntax path to resolve into the array
 * @param  mixed $value the value of the setting that should be set
 * @return mixed        the value of the setting returned
 */
function conf($path, $value = null) {
    global $conf;
    $config = $conf;
    if($value)
        $config = &$conf;
    foreach (explode('.', $path) as $key) {
        if($value) {
            $config = &$config[$key];
            continue;
        }
        $config = $config[$key];
    }
    if($value)
        $config = $value;
    return $config;
}

Now, I am attempting to use this function in the global array itself that is defined in the function.

As you can see above, but when i use the following code:

echo conf('url.up');

it returns

/uploads

not

localhost/uploads

The function works fine. But i'm trying to find a way to use it inside the array correctly.

Upvotes: 0

Views: 45

Answers (1)

Michael Wheeler
Michael Wheeler

Reputation: 660

I think it has to do with the fact that $conf is not defined before you call the conf function. Is something along these lines okay?

$conf = array('site' => array(), 'url' => array());
$conf['url']['site'] = 'localhost';
$conf['url']['up'] = conf('url.site') . '/uploads';

You could use all of the hard-defined array elements as you have before, but add anything that relies on $conf to $conf after $conf has been clearly defined.

Upvotes: 1

Related Questions