3

我正在编写一个 MVC 框架(为了学习和发现,而不是实际打算使用它),我遇到了一个小问题。

我有一个config.php文件:

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

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

$enc_key = 'enc_key'

我通过boot类中的静态方法加载这些:

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;
    }
}

然后像这样加载路线:

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

捕获异常:

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

现在,如果我config.php像这样制作文件,它工作正常

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

并像这样更改方法中的两行:

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

我也尝试过使用$$type而不是${$type}同样的问题。

有什么我忽略的吗?

4

1 回答 1

1

正如所写,这个函数只能被调用一次,因为它使用require_once并且在随后的调用中你将不再引入定义的局部变量config.php。我怀疑您在第二次调用getConfig().

于 2012-06-08T09:54:10.913 回答