PHP Reference ยท Variables and Constants
PHP variable variables
Reference for PHP variable variables: $$name, ${expression}, dynamic properties and methods, array pitfalls with braces, risks and safer alternatives.
A variable variable uses the value of one variable as the name of another. If $field holds the string "city", then $$field means $city. The same idea works for properties ($object->$property), methods ($object->$method()), static members and function calls ($functionName()).
It is a flexible tool for reflection-style code, but it makes programs hard to read, hides variables from static analysis and invites security bugs when the name comes from user input. Most modern code uses arrays or objects instead.
$field = "city"; $city = "Paris"; echo $$field; // Paris echo ${"ci" . "ty"}; // Paris
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
$$name ${expression} $object->$property $object->{expression} $object->$method() Class::$staticMethod() Class::$$staticProperty new $className(...) $functionName(...) ${$arrayName}[0] ${$arrayName[0]}
| Form | Meaning |
|---|---|
$$a |
The variable whose name is the value of $a. |
$$$a |
Two levels of indirection. |
${"abc"} |
The variable $abc, with the name built from any expression. |
${$a}[1] |
Element 1 of the array named by $a. |
${$a[1]} |
The variable named by element 1 of $a. |
Usage notes
- Arrays need braces. In
$$a[1]PHP 7 and later read it as($$a)[1]: take the variable named by$a, then index it. To index$afirst, write${$a[1]}. - Superglobals and
$thiscannot be used as variable variables inside functions and methods:$$namewill not resolve to$_GETor$this. - Scope applies. Inside a function
$$namelooks for a local variable. Use$GLOBALS[$name]for globals. - Never build names from user input.
$$_GET["x"] = ...lets visitors overwrite your variables. Same forextract($_POST). - Static analysis and refactoring tools cannot follow these names, and IDEs cannot rename them.
- Alternatives: use an array (
$data[$key]), an object with__get()/__set(), amatchexpression, orcompact()andextract()in controlled places. - Dynamic names are valid for anything, even names that are impossible to write directly, such as
${"my var"}. - Cost: variable variables defeat some engine optimizations of local variables, so avoid them in hot loops.