Variable Variables and Variable Functions in PHP

Variable Variables and Function Variables in PHP

PHP variable variables are almost never used because they greatly obfuscate any application
that you’re trying to write and can very easily inject a number of bugs into a script.
That being said, this interesting little feature just may be on the Zend PHP Certification Exam.

Variable variables use a variable as the name of another variable.
You may think that these are kind of like a pointer in other languages and I guess they are
except you can’t do any of the fun pointer arithmetic. Here’s a simple example of using the
value of another variable for a variable’s name.

  1.  
  2. $name = ’foo’;
  3. $$name = ’bar’;
  4. echo $foo;
  5. // Displays ’bar’
  6.  

This could also be used to have a number as a variable name (which normally isn’t allowed):

  1.  
  2. $name = ’123’;
  3. $$name = ’456’;
  4. echo ${123};
  5.  

While on the topic of PHP pointer like stuff, it is also possible to use a variable as a function pointer
like in the following example.

  1.  
  2. function myFunc() {
  3.         echo ’myFunc!’;
  4. }
  5. $f = ’myFunc’;
  6. $f(); // will call myFunc();
  7.  

I don’t think I’ll be using any of these features in my applications any time soon but hopefully I
won’t be clueless when taking the Zend PHP Certification Exam to become a Certified Zend Engineer.

3 comments

  1. Nikita Popov says:

    That isn’t half of it 😉

    ${!${”}=func()}[0];

    Guess what it does 🙂

    • admin says:

      I have no idea. Please enlighten me.

      • Nikita Popov says:

        It’s a way to do an function call array dereference (func()[0]) in PHP < 5.4.

        Generally I call this ${!${”}=SOME_EXPRESSION)} technique an "inline expression", i.e. an expression that can occur everywhere a variable can occur too. I would never use this in normal code, but it is a really nice trick when you do code preprocessing 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

*