美文网首页
使用点语法获取配置文件的配置值

使用点语法获取配置文件的配置值

作者: 云龙789 | 来源:发表于2019-02-07 17:58 被阅读6次
  • demo
// 配置文件的数组
$config_file_data = [
    'school' => [
        'class' => [
            'class1'=>[
                'first'=>'here'
            ]
        ]
    ]
];

function config($key)
{
    global $config_file_data;
    if (strpos($key, '.') === false) {
        return $config_file_data[$key];
    }

    foreach (explode('.', $key) as $segment) {
        $config_file_data = $config_file_data[$segment];
    }
    return $config_file_data;
}

$result = config('school.class.class1.first');
$result = config('school');
var_dump($result);

项目中应该是获取配置文件的值才对,此处我只是把获取配置文件数据生咯了,直接使用了 $config_file_data 这个数据。读取配置文件的使用,可以参考这篇文章 自动加载配置文件

思路

  • 先查看有没有 . ,如果没有的话,就是直接返回这个配置文件的所有数据
  • 如果有 .,则遍历每个键(.拼接的其实就是键),然后获取到键对应的值,重写 $config_file_data 这个值。
    此时获取到的就是当前的 $segment 对应的数组,再次遍历,依然是这样循环
  • 其实核心重点就是重写了数组

相关文章

网友评论

      本文标题:使用点语法获取配置文件的配置值

      本文链接:https://www.haomeiwen.com/subject/kdlgsqtx.html