thinkphp C函數的實現原理


在寫一個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';

即可。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM