dongxie9448 2012-06-08 09:47
浏览 63
已采纳

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

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?

  • 写回答

1条回答 默认 最新

  • drdu53813 2012-06-08 09:54
    关注

    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().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数