Home  >  Article  >  Backend Development  >  PHPCMS 中载入配置函数 load_config 什么意思

PHPCMS 中载入配置函数 load_config 什么意思

WBOY
WBOYOriginal
2016-06-06 20:48:441753browse

<code>public static function load_config($file, $key = '', $default = '', $reload = false) {
    static $configs = array();
    if (!$reload && isset($configs[$file])) {
        if (empty($key)) {
            return $configs[$file];
        } elseif (isset($configs[$file][$key])) {
            return $configs[$file][$key];
        } else {
            return $default;
        }
    }
</code>

这段代码中的isset是不是总是为false啊?因为一开始的数组$configs是空的。 主要是不理解 static $configs = array(); 之后 $configs 不就是空数组了么。各位 脚下留情啊,别再踩我了。

回复内容:

<code>public static function load_config($file, $key = '', $default = '', $reload = false) {
    static $configs = array();
    if (!$reload && isset($configs[$file])) {
        if (empty($key)) {
            return $configs[$file];
        } elseif (isset($configs[$file][$key])) {
            return $configs[$file][$key];
        } else {
            return $default;
        }
    }
</code>

这段代码中的isset是不是总是为false啊?因为一开始的数组$configs是空的。 主要是不理解 static $configs = array(); 之后 $configs 不就是空数组了么。各位 脚下留情啊,别再踩我了。

局部静态变量会保留前一次执行的值,不会被重新初始化。你的代码没截取完整,紧跟着下面就有$configs赋值的语句,你可以简单的在if判断前面加个print_f($configs);看一下每次调用load_config时$configs的值就知道怎么回事了。

这样做的目的是,在当前执行过程中缓存$configs的值,避免后续比较消耗的file_exists的判断和include操作。

具体原理可参看:TIPI:静态变量

<code>static $configs = array();
</code>

静态变量

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn