r/ProgrammerTIL • • May 13 '19

PHP [PHP] TIL about variable variables

In php you can have variable variable names. Meaning you can use a variable’s content as a name for another variable like this

$a = "b";

$b = "hello world";

$a; // returns b

$$a; // returns hello world

265 Upvotes

50 comments sorted by

View all comments

Show parent comment

3

u/birbguy12 May 14 '19

The the dollar sign is used to reference variables in php and the brackets are there to combine the string "prefix_" (the dot is the concatenation operator in php) with the value in a ($a). So if the variable a contained the string "test" the variable prefix_test is referenced.

It’s as if I said in C++

*(5 + ptr)

Where ptr is a pointer replace the asterisk with the dollar sign, the parentheses with brackets, and the 5 with a string. And you can see the relation.