沃梦达 / 编程问答 / php问题 / 正文

变量处理顺序:PHP 7 中的变化

Variable variables handling order: changes in PHP 7(变量处理顺序:PHP 7 中的变化)

本文介绍了变量处理顺序:PHP 7 中的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随着新的 PHP 7.0.0 的发布,我有点担心所谓的变量"的评估顺序的变化.

With the new PHP 7.0.0 out now, I'm a bit worried about the changes in evaluation order of the so-called 'variable variables'.

在此页面上,在对变量处理的更改"下有一个表格显示了表达式示例及其在 PHP 5 和 PHP 7 中的处理顺序.列出的四个表达式是:

On this page, under 'Changes to variable handling', a table is displayed with examples of expressions with their handling order in PHP 5 and PHP 7. The four expressions listed are:

$$foo['bar']['baz']
$foo->$bar['baz']
$foo->$bar['baz']()
Foo::$bar['baz']()

给定以下字符串和数组:

Given the following string and array:

$qux = 'quux';
$foo = array('bar' => array('baz' => 'qux'));

$$foo['bar']['baz'] 表中的第一个表达式在 PHP 5 中被解释为一个名为 $foo 中的值的变量的值['bar']['baz'],即$qux的值,即'quux'.

the first expression in the table $$foo['bar']['baz'] is interpreted in PHP 5 as the value of a variable named as the value in $foo['bar']['baz'], thus the value of $qux, which is 'quux'.

但是,据我了解,在 PHP 7 中,相同的表达式将被解释为一个名为 $foo 中的值的变量,因此我希望 PHP 通知将array to string"转换',因为 $foo 是一个数组.

However, in PHP 7, as I understand it, the same expression will be interpreted as a variable named as the value in $foo, thus I expect a PHP Notice for an 'array to string conversion', since $foo is an array.

表中的其他示例似乎是同一主题的变体.

The other examples in the table seem to be a variation of this same theme.

当然,我很好奇为什么 PHP 7 会对此进行更改(具体来说,为什么此更改比向后兼容更重要),但是,这对于 SO 来说不是一个合适的问题.我的问题更实际:

Of course I'm curious to why this is changed in PHP 7 (specifically, why is this change more important than being backwards compatible), however, that's not a suitable question for SO. My question is more practical:

应对这种不兼容性的推荐方法是什么?

当然,在有问题的表达式中添加花括号会有所帮助 (${$foo['bar']['baz']}, $foo->{$bar['baz']}$foo->{$bar['baz']}()Foo::{$bar['baz']}()),但是这样很麻烦,要翻很多旧代码,搜索的次数比较少……

Of course, adding curly braces to the offending expressions will help (${$foo['bar']['baz']}, $foo->{$bar['baz']}, $foo->{$bar['baz']}() and Foo::{$bar['baz']}()), but this is very cumbersome, going through tons of old code, searching for relatively few occurances...

否则,这四个示例是唯一可能的语法变化吗?也就是说,我可以创建一个 RegExp 和 grep 所有有问题的代码吗?可能存在哪些其他变体?

Otherwise, are these four examples the only possible syntax variations? That is, can I create a RegExp and grep all offending code? What other variations might exist?

推荐答案

Rasmus Lerdorf 编写了一个静态分析工具,可以发现这些所谓的统一变量语法问题,称为 Phan https://github.com/etsy/phan

Rasmus Lerdorf wrote a static analysis tool that can spot these so-called Uniform Variable Syntax issues, called Phan https://github.com/etsy/phan

Phan 有选项 -b, --backward-compatibility-checks 来检查潜在的 PHP 5 -> PHP 7 BC 问题.

Phan has the option -b, --backward-compatibility-checks to check for potential PHP 5 -> PHP 7 BC issues.

这篇关于变量处理顺序:PHP 7 中的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:变量处理顺序:PHP 7 中的变化

基础教程推荐