如果作为数组或对象传递,则PHP变量变量不显示

This works with simple variables. But it shows empty result with complex variables. AM I MISSING SOMETHING HERE? or is there anyother way around. Thanks.

#1. This works with simple variables.
$object = "fruit";
$fruit = "banana";

echo $$object;   // <------------ WORKS :outputs "banana".
echo "
";
echo ${"fruit"}; // <------------ This outputs "banana".


#2. With complex structure it doesn't. am I missing something here?
echo "
";
$result = array("node"=> (object)array("id"=>10, "home"=>"earth", ), "count"=>10, "and_so_on"=>true, );
#var_dump($result);

$path = "result['node']->id";
echo "
";
echo $$path; // <---------- This outputs to blank. Should output "10".

Not exactly using variable variables, but if you want to use a variable as the var name, eval should work

$path = "result['node']->id"; eval("echo $".$path.";");

From php.net's page on variable variables

A variable variable takes the value of a variable and treats that as the name of a variable.

The issue is that result['node']->id is not a variable. result is the variable. If you turn on error reporting for PHP notices you will see the following in your output:

PHP Notice: Undefined variable: result['node']->id ...

This can be solved as follows:

$path = "result";
echo "
";
echo ${$path}['node']->id;

The curly braces around $path are required.

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.

If not present the statement is equivalent to

${$path['node']->id}

which will result in the following output:

PHP Warning:  Illegal string offset 'node' in /var/www/html/variable.php on line 18
PHP Notice:  Undefined variable: r in /var/www/html/variable.php on line 18
PHP Notice:  Trying to get property of non-object in /var/www/html/variable.php on line 18