3

私は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'
...

次のようにメソッドの2行を変更します。

if (isset($config[$type])) {
        return $config[$type];

同じ問題の$$type代わりに使ってみました。${$type}

私が見落としているものはありますか?

4

1 に答える 1

1

書かれているように、この関数は と を使用するため、一度だけrequire_once呼び出すことができます。以降の呼び出しでは、 で定義されたローカル変数をconfig.php取り込まないからです。への 2 回目の呼び出しでこのエラーが発生していると思われますgetConfig()

于 2012-06-08T09:54:10.913 に答える