开发者

PHP: Using a variable name, doesn't work on arrays?

开发者 https://www.devze.com 2023-01-22 15:13 出处:网络
I\'m trying to figure out why this works: $joe = \"hey joe\"; $something = \"joe\"; print_r(${$something});

I'm trying to figure out why this works:

$joe = "hey joe";
$something = "joe";
print_r(${$something});

But this doesn't:

$joe["where_you_going"] = "hey joe";
$something = "joe[where_you_going]开发者_开发技巧";
print_r(${$something});

Why is this? Is there a way to do what I attempted in the second example?


Variable variables is a special feature in PHP that permits your first example: http://php.net/manual/en/language.variables.variable.php. It is not an eval which is why it does not work in the second example.

In the second example joe[where_you_going] there's the name of an array, the bracket operator and the name of the index. You can't combine just combine all three since they require operations (indexing into an array) and not just naming. You could do:

$joe["where_you_going"] = "hey joe";
$something = "joe";
$something_else = "where_you_going";
print_r(${$something}[$something_else]);


No, you can't do it like that.

The PHP idea of "variable variables" is usually better done as arrays anyway.


The variable variable syntax does not allow this.
Would it make sense in your case to do one of these things instead?

Use a variable as the array index:

$joe["where_you_going"] = "hey joe";
$something = "where_you_going";
print_r($joe[$something]);


Use a variable as the name of the array and another as the index:

$joe["where_you_going"] = "hey joe";
$something1 = "joe";
$something2 = "where_you_going";
print_r(${$something1}[$something2]);


Use eval to evaluate the whole expression:

$joe["where_you_going"] = "hey joe";
$something = '$joe["where_you_going"]';
print_r(eval("return {$something};"));
0

精彩评论

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