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

标签 php class-method require-once variable-variables

我正在编写一个 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() 时收到此错误。

关于php - 来自必需/包含文件的 PHP 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10946551/

相关文章:

php - 如果 MySQL 行包含数组中的变量,请更新它?

python - 将装饰器附加到类中的所有函数

ios - 如何访问类方法?

python - 尝试调用类方法的代码中的各种错误

PHP 命名空间不需要文件?

php - 你能在 php 中递归地运行 require_once 吗?

requireonce中的PHP绝对路径

php 正则表达式(过滤器?)不应使用正则表达式的地方

php - 在 PHP 中使用 mysql LOAD 语句失败,但通过命令行执行此操作可以

php - MySql - 使用 IF 和 JOIN 插入