Variable variables are somewhat complicated to use, and even more complicated to explain, so you might need to reread this section a few times before it makes sense. Variable variables allow you to access the contents of a variable without knowing its name directly - it is like indirectly referring to a variable. Consider this piece of code:
<?php $bar = 10; $foo = "bar" ?>
There are two ways we can output the value of $bar here. We can either use print $bar, which is quite straightforward, or we can take advantage of the concept of variable variables, and use print $$foo;. That's right - two dollar signs.
By using $$foo, PHP will look up the contents of $foo, convert it to a string, then look up the variable of the same name, and return its value. In the example above, $foo contains the string "bar", so PHP will look up the variable named $bar and output its value - in this case, 10.
Variable variables are fairly clumsy to use, but they can be helpful when you are stuck. Furthermore, they only really get more clumsy the more indirection you use. For example, this next script outputs "Variable!" four times, but I hope you agree it is not very easy to read!
<?php $foo = "Variable!\n"; $bar = "foo"; $wom = "bar"; $bat = "wom"; print $foo; print $$bar; print $$$wom; print $$$$bat; ?>
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Superglobals >>
Previous chapter: Variable scope
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.