Heim  >  Artikel  >  Backend-Entwicklung  >  laravel - php变量解析

laravel - php变量解析

WBOY
WBOYOriginal
2016-08-18 09:15:54934Durchsuche

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

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

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

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

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

回复内容:

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

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

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

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

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

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

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

我给你找个代码好吧。

<code> 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;
        }
    }</code>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn