PHP variable variable not showing if passed as array or object

This works with simple variables. But it shows empty result with complex variables. AM I CAN'T GET HERE? or is there some other way. Thank.

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

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


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

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

      

+3


source to share


2 answers


It is wrong to use variable variables, but if you want to use a variable as a var name, eval should work



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

0


source


From php.net page on variables variables

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

The problem is that result['node']->id

it is not a variable. result

- variable. If you enable error reporting for PHP notifications, you will see the following in the output:

PHP Note: Undefined variable: result ['node'] โ†’ id ...

This can be solved as follows:

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

      



Requires curly braces around $path

.

To use variable variables with arrays, you have to solve the ambiguity problem. That is, if you are writing $$a[1]

, then you need a parser to know if you want to use it $a[1]

as a variable, or if you want to use it $$a

as a variable, then an index [1]

from that variable. The syntax for solving this ambiguity is ${$a[1]}

for the first case and ${$a}[1]

for the second.

If not, the operator is equivalent to

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

      

which will produce 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

      

0


source







All Articles