Welcome to %s forums

<No. 1 Community for developers, by developers/>

Login Register

Accessing A Variable Dynamically By Name (Variable variables) using PHP

For all PHP related discussion, one of the most popular programming languages on the web.
Post Reply
admin
Site Admin
Posts: 45

Accessing A Variable Dynamically By Name (Variable variables) using PHP

Post by admin » Sun Nov 03, 2019 5:24 pm

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.

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};
Variable variables are useful for mapping function/method calls:

Code: Select all

function add($a, $b) {
 return $a + $b;
}
$funcName = 'add';
echo $funcName(1, 2); // outputs 3
This becomes particularly helpful in PHP classes:

Code: Select all

class myClass {
 public function __construct() {
 $functionName = 'doSomething';
 $this->$functionName('Hello World');
 }
 private function doSomething($string) {
 echo $string; // Outputs "Hello World"
 }
}
It is possible, but not required to put $variableName between {}:

Code: Select all

${$variableName} = $value;
The following examples are both equivalent and output "baz":

Code: Select all

$fooBar = 'baz';
$varPrefix = 'foo';
echo $fooBar; // Outputs "baz"
echo ${$varPrefix . 'Bar'}; // Also outputs "baz"
Using {} is only mandatory when the name of the variable is itself an expression, like this:

Code: Select all

${$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:

Code: Select all

$$$$$$$$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.

Post Reply