laravel - php变量解析
PHPz
PHPz 2017-04-11 09:54:44
[PHP讨论组]

比如现在我有变量 $arr, 他是一个数组

$arr = [
    'news' => [
        'data' => [
            0 => [
                'title' => '名字',
                'content' => '内容'
            ],
        ],
    ],
];

一些框架或模板引擎 都带了解析的功能, 可以通过 arr.news.data[0].title 的方式, 获取到 title 的值, 以及可以对值进行修改。

那么我想知道他是什么原理, 如何 高效、安全、简单 的使用此种表达方式对数组中的值进行获取以及设置呢?

我能想到的是利用文本处理的方式实现的, 不过安全性、效率上应该不算很高。请老师指点。

PHPz
PHPz

学习是最好的投资!

全部回复(2)
ringa_lee

我给你找个代码好吧。

 public static function getValue($array, $key, $default = null)
    {
        if ($key instanceof \Closure) {
            return $key($array, $default);
        }

        if (is_array($key)) {
            $lastKey = array_pop($key);
            foreach ($key as $keyPart) {
                $array = static::getValue($array, $keyPart);
            }
            $key = $lastKey;
        }

        if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array)) ) {
            return $array[$key];
        }

        if (($pos = strrpos($key, '.')) !== false) {
            $array = static::getValue($array, substr($key, 0, $pos), $default);
            $key = substr($key, $pos + 1);
        }

        if (is_object($array)) {
            // this is expected to fail if the property does not exist, or __get() is not implemented
            // it is not reliably possible to check whether a property is accessable beforehand
            return $array->$key;
        } elseif (is_array($array)) {
            return (isset($array[$key]) || array_key_exists($key, $array)) ? $array[$key] : $default;
        } else {
            return $default;
        }
    }
天蓬老师

绝大多数模板引擎都是使用预编译的方式处理的,即输入的模板数据,会将其中变量、循环、条件等符号,转换成标准的PHP语句,之后再执行这些内容。

另外,这些框架或者模板引擎都是开源的,你有时间在这里问人,自己去看看代码早就明白了。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号