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.
-
-
$name = ’foo’;
-
$$name = ’bar’;
-
echo $foo;
-
// Displays ’bar’
-
This could also be used to have a number as a variable name (which normally isn’t allowed):
-
-
$name = ’123’;
-
$$name = ’456’;
-
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.
-
-
function myFunc() {
-
echo ’myFunc!’;
-
}
-
$f = ’myFunc’;
-
$f(); // will call myFunc();
-
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.
That isn’t half of it 😉
${!${”}=func()}[0];
Guess what it does 🙂
I have no idea. Please enlighten me.
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 🙂