Variable variables

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:

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

    $foo = "Variable!\n";
    $bar = "foo";
    $wom = "bar";
    $bat = "wom";
    print $foo;
    print $$bar;
    print $$$wom;
    print $$$$bat;


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

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

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.