PHP Question: Variable Reference

17th April 2011

Question

What does the following code snipped print?

  1. $a = 5;
  2. $b = 'a';
  3. 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. $a = 5;
  2. $b = 'a';
  3. $c = 'b';
  4. $d = 'c';
  5. $e = 'd';
  6. $f = 'e';
  7.  
  8. print $$b;
  9. print $$$c;
  10. print $$$$d;
  11. print $$$$d;
  12. print $$$$$e;
  13. print $$$$$$f;

Comments

Permalink

It prints 5. That's because $$b is actually '$' + 'a' so the result is print $a

Mihai Baboi (Mon, 04/18/2011 - 09:44)

Add new comment

The content of this field is kept private and will not be shown publicly.