2012-06-08 99 views
3

我正在编写一个MVC框架(出于学习和发现的目的而不是实际打算使用它),并且遇到了一个小问题。来自所需/包含文件的PHP中的变量变量

我有一个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}与同样的问题。

有什么我可以忽略的吗?

回答

1

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

+0

我纠正了,我把它改为'require',它工作,对不起! –

+0

好吧马克这个人回答正确!另外,添加不需要该函数中的文件。要求在函数之外,并将配置作为参数传递。 – Galen

+0

我最初需要index.php页面中的文件,我不知道为什么我还是不这样做,我想我只是在尝试新事物! –