开发者

can array values be accessed by variable variables?

I have an array which I can only access correctly via variable variables, like so:

$foo['bar'] = "pie";

$fixed_name_variable = "foo['bar']";

echo $$fixed_name_variable;

Which in theroy echo's pie. Except it's just not returning anything. So I need to know if this approach is actually workable or if I need a rethink on it.

Just noticed. On the se开发者_StackOverflow中文版cond line, should the bar be in quotes?


Although I hate to encourage this behaviour, you can use eval to achieve what you to a limited extent.

$foo['bar'] = "pie";
$fixed_name_variable = "foo['bar']";

$a = eval("return $$fixed_name_variable;"); 
echo $a; //outputs "pie"


$foo[$key_var] should work, unless I misunderstood your question?


No, I don't think this is possible. The only thing (obviously) possible is to use a variable index, and access $foo[$bar].

However, using variable variables is usually very bad practice anyway - especially because they make debugging and automatic documentation / variable lookup so terribly difficult. It's usually best not to use them, but to use an array instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜