KdgDev
KdgDev

Reputation: 14529

PHP variable variables in {} symbols

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?

Upvotes: 4

Views: 228

Answers (4)

kandelvijaya
kandelvijaya

Reputation: 1585

$this->{$toShow}();

Break it down as below:

First this is a object oriented programming style as you got to see $this and ->. Second, {$toShow}() is a method(function) as you can see the () brackets.

So now {$toShow}() should somehow be parsed to a name like 'compute()'. And, $toShow is just a variable which might hold a possible function name. But the question remains, why is {} used around.

The reason is {} brackets substitues the value in the 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 

Upvotes: 0

Marc B
Marc B

Reputation: 360712

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.

Upvotes: 4

Gumbo
Gumbo

Reputation: 655339

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"

Upvotes: 3

Felix Kling
Felix Kling

Reputation: 816552

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]}

Upvotes: 4

Related Questions