PHP variable variables in {} characters

I get the basics of variable variables, but I saw that the syntax just knows that my mind is a little scary.

$this->{$toShow}(); 

I really don’t see what the {} characters do there. Do they have any special meaning?

+4
source share
4 answers

The PHP parser is not greedy. {} Used to indicate what should be considered part of a variable reference and what not. Consider this:

 $arr = array(); $arr[3] = array(); $arr[3][4] = 'Hi there'; echo "$arr[3][4]"; 

Pay attention to double quotes. You expected this to output Hi there , but actually you see Array[4] . This is due to the frivolity of the analyzer. It will check only one level of indexing the array when interpolating variables into a string, so this was really visible:

 echo $arr[3], "[4]"; 

But by doing

 echo "{$arr[3][4]}"; 

forces PHP to treat everything inside curly brackets as a variable reference, and you get the expected Hi there .

+4
source

They tell the parser where the variable name begins and ends. In this particular case, this may not be necessary, but consider this example:

 $this->$toShow[0] 

What should the parser do? Is $toShow array or $this->$toShow ? In this case, the variable is first resolved, and the array index is applied to the resulting property.

So, if you really want to access $toShow[0] , you need to write:

 $this->{$toShow[0]} 
+4
source

These braces can be used to use expressions to indicate the identifier of a variable instead of the value of variables:

 $var = 'foo'; echo ${$var.'bar'}; // echoes the value of $foobar echo $$var.'bar'; // echoes the value of $foo concatenated with "bar" 
+3
source
 $this->{$toShow}(); 

Break it below:

First up is the object oriented programming style that you see $this and -> . Secondly, {$toShow}() is a method (function), since you can see brackets ().

So now {$toShow}() should somehow analyze a name like " compute() ". And $ toShow is just a variable that may contain a possible function name. But the question remains, why {} is used around.

Reason: {} brackets replace the value in place. To clarify,

 $toShow="compute"; 

So,

 {$toShow}(); //is equivalent to compute(); 

but this is not true:

 $toShow(); //this is wrong as a variablename is not a legal function name 
0
source

All Articles