• 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';

    即可。

  • 相关阅读:
    iOS controller 和 window 图层
    iOS CGAffineTransform 仿射变换
    iOS UIButton的UIEdgeInsets
    iOS UI的动态布局
    iOS 栅格动态布局
    iOS 系统键盘几个类型
    iOS 金融类高精度处理
    Sublime Text (崇高文本)
    iOS 静态库——制作bundle
    iOS 静态库——制作Framework
  • 原文地址:https://www.cnblogs.com/trying/p/3289650.html
Copyright © 2020-2023  润新知