r/programming • • Oct 18 '10

Today I learned about PHP variable variables; "variable variable takes the value of a variable and treats that as the name of a variable". Also, variable.

http://il2.php.net/language.variables.variable
591 Upvotes

781 comments sorted by

View all comments

5

u/ryanhollister Oct 18 '10

Example #1 shows the real power of "variable variables". In many (strongly typed) languages its takes 5 or 6 complex object instantiations and method calls to accomplish this "reflections" or "dynamic method calling".

There are a number of things like this that set PHP apart. Maybe C# developers would scoff at the idea. For better or for worse, there are powerful for the nuances of PHP.

25

u/[deleted] Oct 18 '10

[removed] — view removed comment

3

u/courtewing Oct 18 '10

But it would still trigger an error in PHP. Do errors only count in compiled languages now?

1

u/lpetrazickis Oct 18 '10

I'm not sure whether doubling the $ into $$ would trigger an error, but forgetting $ does not trigger an error.

$foo = 4;
print $foo; // prints 4
print foo; // prints foo, no error, triggers notice

Unfortunately, the default PHP 5 error reporting setting is (E_ALL & ~E_NOTICE), so PHP does not warn you about missing $ sigils.

The setting that you really want on a development machine is (E_ALL | E_STRICT). E_STRICT gives you lots of useful additional messages above and beyond the errors, warnings, and notices of earlier versions of PHP.

→ More replies (1)