变量处理变更

PHP7版本对变量解析机制做了调整,调整如下:

1. 可变变量, 属性方法引用现在按照从左到右的语义进行解释. 一些例子:
$$foo['bar']['baz'] // interpreted as ($$foo)['bar']['baz']
$foo->$bar['baz']   // interpreted as ($foo->$bar)['baz']
$foo->$bar['baz']() // interpreted as ($foo->$bar)['baz']()
Foo::$bar['baz']()  // interpreted as (Foo::$bar)['baz']()

恢复之前的语义需显式加入花括号:

${$foo['bar']['baz']}
$foo->{$bar['baz']}
$foo->{$bar['baz']}()
Foo::{$bar['baz']}()
2. global关键词现在只接受简单变量. 形如
global $$foo->bar;

现在需要改写:

global ${$foo->bar};
3. 圆括号不再影响变量或者函数调用语义.

以下代码示例, 传递函数调用结果给by-reference函数

function getArray() { return [1, 2, 3]; }

$last = array_pop(getArray());
// Strict Standards: Only variables should be passed by reference
$last = array_pop((getArray()));
// Strict Standards: Only variables should be passed by reference

无论是否使用圆括号, 现在都将抛出strict standards错误. 之前版本的不会报错.

4. 引用赋值时, 数组元素或对象属性的创建顺序发生变更.
$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);
----------      
PHP7 $array == ["a" => 1, "b" => 1]
PHP5 $array == ["b" => 1, "a" => 1]

Relevant RFCs: uniform_variable_syntax abstract_syntax_tree

results matching ""

    No results matching ""