tags:

views:

73

answers:

3

I get the basics of variable variables, but I saw a syntax just know, which bogles my mind a bit.

$this->{$toShow}();

I don't really see what those {} symbols are doing there. Do they have any special meaning?

+3  A: 

They tell the parser, where a variable name starts and ends. In this particular case it might not be needed, but consider this example:

$this->$toShow[0]

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

So if you actually want to access $toShow[0], you have to write:

$this->{$toShow[0]}
Felix Kling
+2  A: 

These curly braces can be used to use expressions to specify the variable identifier instead of just a variable’s value:

$var = 'foo';
echo ${$var.'bar'};  // echoes the value of $foobar
echo $$var.'bar';    // echoes the value of $foo concatenated with "bar"
Gumbo
+2  A: 

PHP's variable parser isn't greedy. The {} are used to indicate what should be considered part of a variable reference and what isn't. Consider this:

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

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

Notice the double quotes. You'd expect this to output Hi there, but you actually end up seeing Array[4]. This is due to the non-greediness of the parser. It will check for only ONE level of array indexing while interpolating variables into the string, so what it really saw was this:

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

But, doing

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

forces PHP to treat everything inside the braces as a variable reference, and you end up with the expected Hi there.

Marc B