PHP Question: Variable Reference
Published by philipnorton42 on Sun, 04/17/2011 - 13:15Question
What does the following code snipped print?
1 2 3 | $a = 5; $b = 'a'; print $$b; |
Answer
This will print "5" because $$b tells PHP to use the value of the $b variable as a variable name, so as the value of $b is 'a' we are really looking at the value of $a; the $$b above could be replaced by $a and have the same output. This variable variable feature is a little obscure but it is useful to use in certain circumstances.
This can be taken a step further by using multiple levels of reference to access a variable by adding more dollar signs to the front of the variable name. All of the following will print out 5 because all of the print statements will point back to the variable $a.
1 2 3 4 5 6 7 8 9 10 11 12 13 | $a = 5; $b = 'a'; $c = 'b'; $d = 'c'; $e = 'd'; $f = 'e'; print $$b; print $$$c; print $$$$d; print $$$$d; print $$$$$e; print $$$$$$f; |
Category:
Comments
I know this one. I hope...
Mihai Baboi (not verified) - Mon, 04/18/2011 - 10:44It prints 5. That's because
$$bis actually '$' + 'a' so the result isprint $aAdd new comment