PHP Variables
Accessing A Variable Dynamically By Name
Variables can be accessed via dynamic variable names. The name of a variable can be stored in another variable, allowing it to be accessed dynamically. Such variables are known as variable variables.
To turn a variable into a variable variable, you put an extra $ put in front of your variable.
$variableName = 'foo';
$foo = 'bar';
The following are all equivalent, and all output "bar":
echo $foo;
echo ${$variableName};
echo $$variableName;
Output
foo
foo
Variable variables are useful for mapping function/method calls:
function add($a, $b) {
return $a + $b;
}
$funcName = 'add';
echo $funcName(1, 2);
Output
This becomes particularly helpful in PHP classes:
class myClass {
public function __construct() {
$functionName = 'doSomething';
$this->$functionName('Hello World');
}
private function doSomething($string) {
echo $string; // Outputs "Hello World"
}
}
Output
The following examples are both equivalent and output "baz":
$fooBar = 'baz';
$varPrefix = 'foo';
echo $fooBar;
echo ${$varPrefix . 'Bar'};
Output
baz
Using {} is only mandatory when the name of the variable is itself an expression, like this:
${$variableNamePart1 . $variableNamePart2} = $value;
It is nevertheless recommended to always use {}, because it's more readable.
While it is not recommended to do so, it is possible to chain this behavior:
$$$$$$$$DoNotTryThisAtHomeKids = $value;
It's important to note that the excessive usage of variable variables is considered a bad practice by many developers. Since they're not well-suited for static analysis by modern IDEs, large codebases with many variable variables (or dynamic method invocations) can quickly become difficult to maintain.