PHP $$var['index'] = 某物;失败了,尽管我认为它会像 $$var = something; 一样工作;做
PHP $$var['index'] = something; fails, although I thought it would work just like $$var = something; does
我试图在 PHP 中使用 $$ 语法来访问数组,我们可以将一个变量的名称放在另一个变量中并访问该变量。
我以前以不同的方式多次使用过这种语法,但令我惊讶的是这对我不起作用并且浪费了很多时间。
这里是复制我的问题的示例代码:
$test=array(
'a'=>array(array(1,2,3),array(4,5,6),array(7,8,9))
);
$var = 'test';
var_dump($$var);
var_dump($$var['a']);
行 var_dump($$var)
按预期工作,但我收到警告:第 var_dump($$var['a']);
行的非法字符串偏移量 'a' 和 var_dump 仅打印 null
为什么这不起作用?我在这里做错了什么?
如果数组不支持语法,是否有任何解决方法?
您的 $$var['a']
相当于 ${$var['a']}
。不是 ${$var}['a']
。后者是您正在寻找的解决方法语法。
引用 PHP Manual on Variable Variables:
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1]
then the parser needs to know if you meant to use $a[1]
as a variable, or if you wanted $$a
as the variable and then the [1]
index from that variable. The syntax for resolving this ambiguity is: ${$a[1]}
for the first case and ${$a}[1]
for the second.
我试图在 PHP 中使用 $$ 语法来访问数组,我们可以将一个变量的名称放在另一个变量中并访问该变量。
我以前以不同的方式多次使用过这种语法,但令我惊讶的是这对我不起作用并且浪费了很多时间。
这里是复制我的问题的示例代码:
$test=array(
'a'=>array(array(1,2,3),array(4,5,6),array(7,8,9))
);
$var = 'test';
var_dump($$var);
var_dump($$var['a']);
行 var_dump($$var)
按预期工作,但我收到警告:第 var_dump($$var['a']);
行的非法字符串偏移量 'a' 和 var_dump 仅打印 null
为什么这不起作用?我在这里做错了什么? 如果数组不支持语法,是否有任何解决方法?
您的 $$var['a']
相当于 ${$var['a']}
。不是 ${$var}['a']
。后者是您正在寻找的解决方法语法。
引用 PHP Manual on Variable Variables:
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write
$$a[1]
then the parser needs to know if you meant to use$a[1]
as a variable, or if you wanted$$a
as the variable and then the[1]
index from that variable. The syntax for resolving this ambiguity is:${$a[1]}
for the first case and${$a}[1]
for the second.