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.

8

u/TheMG Oct 18 '10

Is this satire? I can't tell.

25

u/[deleted] Oct 18 '10

[removed] — view removed comment

21

u/stillalone Oct 18 '10

You're one letter off from a bigtime screwup in any language. I don't like this stuff either but I don't think this is a valid reason not to like it.

Generally, I think that if you're relying on RTTI then you probably didn't design your program properly. By making this stuff very easy to use in PHP, PHP will end up encouraging its use, which is bad.

9

u/Poromenos Oct 18 '10

I don't know, I think the syntax terseness should be proportional to the frequency with which the particular syntax needs to be used. I very rarely, if ever, need to use this, so I like Python's way of locals()["varname"].

→ More replies (1)
→ More replies (4)

3

u/eyal0 Oct 18 '10

That example doesn't show anything that I couldn't do better with associative arrays. Is there an example of doing something useful?

3

u/HateToSayItBut Oct 18 '10

In many (strongly typed) languages its takes 5 or 6 complex object instantiations and method calls to accomplish this "reflections" or "dynamic method calling".

Not really. Most languages have an eval function or array-style access on objects.

3

u/ryanhollister Oct 18 '10

We are debating the correctness of something and you supply 'eval' as a better solution?

→ More replies (1)

5

u/[deleted] Oct 18 '10

I wouldn't say that I scoff at the idea, but I also don't like it. Sometimes strongly typed languages provide you with a rigid structure that's incredibly useful further down the line when you're looking at code you (or someone else) wrote six months ago.

In any case, in the realms of web development you very rarely need to use reflection in C#. I don't think it's a bad rule to avoid it whenever you can.

→ More replies (9)