PHP: Variable variables?

Posted by: Jordan in ProgrammingPHP on

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:

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:


 
  1. $someVar = "hello";
  2. $newVar = "someVar";
  3.  
  4. 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.


 
  1. function someFunction() {
  2.     echo "This is some function!";
  3. }
  4.  
  5. $someVar = 'someFunction';
  6. $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.




Trackback(0)
Comments (3)add comment

John said:

What kind of security errors?
 
report abuse
vote down
vote up
July 05, 2008
Votes: +0

Jordan said:

With bad code and variable variables (such as accepting variable names from an external source) anything is possible.

You should read my blog about the Security class from zend: http://blog.codecall.net/compo...binar.html

 
report abuse
vote down
vote up
July 05, 2008 | url
Votes: +0

dargueta said:

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
July 06, 2008
Votes: +0

Write comment
quote
bold
italicize
underline
strike
url
image
quote
quote
smile
wink
laugh
grin
angry
sad
shocked
cool
tongue
kiss
cry
smaller | bigger

busy