4

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?

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

3

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"

Comments

0
$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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.