3.7 Variable variablesThis is NOT the latest copy of this book; click here for the latest version.
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; ?>
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|