| PHP: Variable variables? Posted by: Jordan in Programming, PHP on Jul 05, 2008 |
An interesting topic in PHP is variable variables. This feature of PHP is rarely utilized but very powerful. A variable variables is a variable name contained within another variable. From the PHP Manual:
An example would be:

which would output:
hello
Take a look at $newVar - it holds the name of another variable, someVar. $someVar holds the value of hello. The curly brackets around $newVar are the standard execution method for variable variables. You can also do this with functions.

which will output:
This is some function!
Which is similar in nature but not entirely the same.
Word of Caution
Using variable variables to often can result in unreadable code, security errors and mistakes. You should use this feature with care.
Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically.
An example would be:

- $someVar = "hello";
- $newVar = "someVar";
- echo ${$newVar};
$someVar = "hello";
$newVar = "someVar";
echo ${$newVar};
$newVar = "someVar";
echo ${$newVar};
which would output:
hello
Take a look at $newVar - it holds the name of another variable, someVar. $someVar holds the value of hello. The curly brackets around $newVar are the standard execution method for variable variables. You can also do this with functions.

- function someFunction() {
- echo "This is some function!";
- }
- $someVar = 'someFunction';
- $someVar();
function someFunction() {
echo "This is some function!";
}
$someVar = 'someFunction';
$someVar();
echo "This is some function!";
}
$someVar = 'someFunction';
$someVar();
which will output:
This is some function!
Which is similar in nature but not entirely the same.
Word of Caution
Using variable variables to often can result in unreadable code, security errors and mistakes. You should use this feature with care.
Set as favorite
Bookmark
Email This
Hits: 351
Trackback(0)
|
John
July 05, 2008 24.191.57.21 Votes: +0 |
What kind of security errors? report abuse
vote down
vote up
|
|
Jordan
July 05, 2008 209.42.180.9 Votes: +0 |
With bad code and variable variables (such as accepting variable names from an external source) anything is possible. report abuse
vote down
vote up
|
|
dargueta
July 06, 2008 70.131.130.194 Votes: +0 |
Just out of curiosity...why would someone change variable names in the middle of a program? Isn't it better to create a new variable? I can see using it as a function pointer, but for variables I think it's just something to add confusion. report abuse
vote down
vote up
|
Write comment