zoukankan      html  css  js  c++  java
  • 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';

    即可。

  • 相关阅读:
    51 Nod 1068 Bash游戏v3
    51 Nod Bash 游戏v2
    51 Nod 1073 约瑟夫环
    UVA 12063 Zeros and ones 一道需要好好体会的好题
    51 Nod 1161 Partial sums
    2018中国大学生程序设计竞赛
    UVA 11971 Polygon
    UVA 10900 So do you want to be a 2^n-aire?
    UVA 11346 Possibility
    python with as 的用法
  • 原文地址:https://www.cnblogs.com/trying/p/3289650.html
Copyright © 2011-2022 走看看