PHP 中来自必需/包含文件的变量变量


Variable Variables in PHP from required / included files

我正在编写一个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}同样的问题。

我忽略了什么吗?

如前所述,此函数只能调用一次,因为它使用 require_once 并且在后续调用中,您将不再引入 config.php 中定义的局部变量。我怀疑您在第二次致电getConfig()时收到此错误。