Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP variable variables in {} symbols

Tags:

php

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?

like image 775
KdgDev Avatar asked Dec 22 '22 00:12

KdgDev


2 Answers

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.

like image 174
Marc B Avatar answered Dec 24 '22 13:12

Marc B


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]}
like image 43
Felix Kling Avatar answered Dec 24 '22 13:12

Felix Kling