To turn a variable into a variable variable, you put an extra $ put in front of your variable.
Code: Select all
$variableName = 'foo';
$foo = 'bar';
// The following are all equivalent, and all output "bar":
echo $foo;
echo ${$variableName};
echo $$variableName;
//similarly,
$variableName = 'foo';
$$variableName = 'bar';
// The following statements will also output 'bar'
echo $foo;
echo $$variableName;
echo ${$variableName};
Code: Select all
function add($a, $b) {
return $a + $b;
}
$funcName = 'add';
echo $funcName(1, 2); // outputs 3
Code: Select all
class myClass {
public function __construct() {
$functionName = 'doSomething';
$this->$functionName('Hello World');
}
private function doSomething($string) {
echo $string; // Outputs "Hello World"
}
}
Code: Select all
${$variableName} = $value;
Code: Select all
$fooBar = 'baz';
$varPrefix = 'foo';
echo $fooBar; // Outputs "baz"
echo ${$varPrefix . 'Bar'}; // Also outputs "baz"
Code: Select all
${$variableNamePart1 . $variableNamePart2} = $value;
While it is not recommended to do so, it is possible to chain this behavior:
Code: Select all
$$$$$$$$DoNotTryThisAtHomeKids = $value;
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.