我正在编写一个 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/