PHP 5.6 中的动态变量行为
Dynamic variable behavior in PHP 5.6
我在下面创建了代码,但仅适用于 PHP 7+ 版本。
我需要在此处更改什么才能使 $$variablename[$key]
在 5.6 版本上工作?
$g_module_id_bar_1['id'] = 5;
$i = 1;
$variablename = 'g_module_id_bar_'.$i;
$key = 'id';
echo $$variablename[$key]; // doesn't work
结果应该是:5
在PHP5中,你应该写
echo ${$variablename}[$key];
你问题中的代码在 PHP 7 中工作的原因是 PHP 7 在处理间接变量的方式上引入了变化:
Indirect access to variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the previous mix of special cases. The table below shows how the order of evaluation has changed.
更具体地说,表达式如下:
$$foo['bar']['baz']
在 PHP 5 中被解释为:
${$foo['bar']['baz']}
在 PHP 7 中:
($$foo)['bar']['baz']
我在下面创建了代码,但仅适用于 PHP 7+ 版本。
我需要在此处更改什么才能使 $$variablename[$key]
在 5.6 版本上工作?
$g_module_id_bar_1['id'] = 5;
$i = 1;
$variablename = 'g_module_id_bar_'.$i;
$key = 'id';
echo $$variablename[$key]; // doesn't work
结果应该是:5
在PHP5中,你应该写
echo ${$variablename}[$key];
你问题中的代码在 PHP 7 中工作的原因是 PHP 7 在处理间接变量的方式上引入了变化:
Indirect access to variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the previous mix of special cases. The table below shows how the order of evaluation has changed.
更具体地说,表达式如下:
$$foo['bar']['baz']
在 PHP 5 中被解释为:
${$foo['bar']['baz']}
在 PHP 7 中:
($$foo)['bar']['baz']