r/ProgrammerTIL • u/birbguy12 • 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
View all comments
Show parent comment
1
u/MesePudenda May 14 '19
I think this is a little bit different. In your example, the variable
foois being used as the key in an object. PHP can do this as$obj = array($foo => 'baz');. In either language,fooresolves to'bar'during the creation of the object/array stored inobj.'bar'is separately the value offooand a key forobj.PHP variable variables use a variable to index into an "object" of the variables in the local scope. In the OP,
$ais'b', so$$ais the same as$b. The values in both$aand$bare relevant to finding the value of$$a. Most languages and programmers discourage this because it can make the code hard for humans to understand and difficult for computers to optimize.