MOCKSTACKS
EN
Questions And Answers

More Tutorials









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

bar
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

3

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

"Hello World"

The following examples are both equivalent and output "baz":


$fooBar = 'baz';
$varPrefix = 'foo';

echo $fooBar; 
echo ${$varPrefix . 'Bar'};

Output

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



Conclusion

In this page (written and validated by ) you learned about PHP Variables . What's Next? If you are interested in completing PHP tutorial, your next topic will be learning about: PHP Data Types.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.