thinkphp C関数の実現原理

5593 ワード

php原生関数を書く時、thinkphpのC関数を使ってデータベースの配置を読み取るのがとても便利だと思い出して、そこでソースコードの実現を見て、原理はとても簡単で、分かち合います:
次はcommonです.php、C関数を実現しました:
if(is_file("config.php") )
{
    // config.php        
    // C         ,           $_config,                 
    C(include 'config.php');
}
//      
function C($name=null, $value=null) {
    //      ,           $)config   
    static $_config = array();
    //         
    if (empty($name))   return $_config;
    //            
    if (is_string($name)) {
        if (!strpos($name, '.')) {
            $name = strtolower($name);
            if (is_null($value))
                return isset($_config[$name]) ? $_config[$name] : null;
            $_config[$name] = $value;
            return;
        }
        //            
        $name = explode('.', $name);
        $name[0]   =  strtolower($name[0]);
        if (is_null($value))
            return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : null;
        $_config[$name[0]][$name[1]] = $value;
        return;
    }
    // include 'config.php'         ,      C     ,       ,           $_config 
    if (is_array($name)){
        return $_config = array_merge($_config, array_change_key_case($name));
    }
    return null; //       
}

使用方法は簡単です:C関数を使用する必要がある場所:
include 'common.php';
できます.