문제

I am writing a MVC Framework (for the purpose of learning and discovery as opposed to actually intending to use it) and I have came across a slight problem.

I have a config.php file:

$route['default'] = 'home';

$db['host'] = 'localhost';
$db['name'] = 'db-name';
$db['user'] = 'user-name';
$db['pass'] = 'user-pass';

$enc_key = 'enc_key'

I load these via a static method in my boot class:

public static function getConfig($type) {
    /**
     * static getConfig method gets configuration data from the config file
     *
     * @param string $type - variable to return from the config file.
     * @return string|bool|array - the specified element from the config file, or FALSE on failure
     */
    if (require_once \BASE . 'config.php') {
        if (isset(${$type})) {
            return ${$type};
        } else {
            throw new \Exception("Variable '{$type}' is undefined in " . \BASE . "config.php");
            return FALSE;
        }
    } else {
        throw new \Exception("Can not load config file at: " . \BASE . 'config.php');
        return FALSE;
    }
}

and then load the route like so:

public function routeURI($uri) {
    ...
    $route = $this::getConfig('route');
    ...
}

which catches the exception:

"Variable 'route' is undefined in skeleton/config.php"

now, it works fine if I make the config.php file like so

$config['route']['default'] = 'home'
...

and change the two lines in the method like so:

if (isset($config[$type])) {
        return $config[$type];

I have also tried using $$type instead of ${$type} with the same problem.

Is there something I am overlooking?

도움이 되었습니까?

해결책

As written, this function can be called only once, because it uses require_once and on subsequent calls you won't bring in the local variables defined in config.php anymore. I suspect you are getting this error on your second call to getConfig().

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top