带数组的双美元变量 [英] Double dollar variables with arrays
问题描述
我正在尝试使用双美元语法访问数组的第一项,但它无法像我希望的那样工作.
I am trying to access the first item of an array using the double dollar syntax, but it doesn't work as I would want it to.
<?php
$a = 'test';
$test = ['a', 'b'];
echo $$a[0];
这会说变量 t 未定义,因为它首先呈现 $a[0](这是一个t"),然后尝试访问名为 $t 的变量作为结果.
This will say that the variable t is undefined, because it renders the $a[0] first (which is a "t") and then tries to access the variable called $t as a result.
我想要的是与这些类似的东西(以下代码片段都不起作用,它们只是我尝试过的东西,以说明这个想法)
What I want is something along the line of these (none of the following snippets work, they are just things I tried, to illustrate the idea)
<?php
$a = 'test';
$test = ['a', 'b'];
echo {$$a}[0];
或者
<?php
$a = 'test';
$test = ['a', 'b'];
echo ${$$a}[0];
基本上,告诉 PHP $$a 部分优先.
Basically, tell PHP that the $$a part gets priority.
推荐答案
你们非常接近.您需要告诉 PHP 单独评估 $a
.试试:
You were very close. You need to tell PHP to evaluate the $a
alone. Try:
<?php
$a = 'test';
$test = ['a', 'b'];
echo ${$a}[0];
这篇关于带数组的双美元变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!