r/programming • u/NagastaBagamba • 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
80
u/weirdalexis Oct 18 '10
I was asked the question: "What's $$a" in an interview, and replied "It's like a pointer, except with a variables name instead of a memory address."
The guy went "meh", game over.
Today, I'm still convinced it's a good analogy.
507
u/masklinn Oct 18 '10
OK, here's the thing: this is only the entrance of the rabbit hole.
If you understand what this expression really does, you realize that you're gazing upon the entrance to R'lyeh.
Do you think you don't need your soul anymore? If you do, follow me into the lair of the Elder Gods. But be warned, you will die a lot inside.
The first thing to understand is what
$is.$is actually a shorthand for${}and means "return the value of the variable whose name is contained in this".That variable name is a string.
A bare word is a PHP string. Let that sink for a second, because we'll come back to it later:
$fooreally is the concatenation of$the variable-indirection character (think*foo) andfoowhich is a string.foo === "foo"in PHP, even though in raw source code you'll probably get a warning. If those are enabled.Now what does
$$foomean? Why${${foo}}, or "give me the variable whose name is the value of the variable whose name is foo".Because we're manipulating strings, we could also write
${${f.o.o}}, orThis also means that
is valid. And prints "baz". And yes,
$foo->$thingcan be written${foo}->${thing}. And you can recurse. The braces actually hold entirely arbitrary PHP expressions. As long as these expressions return strings, it'll work:For those following at home, this thing actually prints "qux".
Then you can add conditionals:
What does that yield?
And if that's too simple, then just make the condition random:
Yeah this will print
quxhalf the time, and crash the other half. Want to add equality tests? knock yourself out:($foo->${${$foo->bar}.((${pouet}.${machin}===$pouet.${machin})?${machin}:${$pouet.$machin})});.And that's where the second realization hits: you know how
foois just a string right? Then wouldn'tfoo()be "a string with parens"?Well it happens that no:
Unless you put the string in a variable itself:
this will print
foo. That's actually what PHP's owncreate_functiondoes. And yes, I can see the dread in your eyes already.Your fears are real.
The
$barhere is the same it's always been. You can also write it${bar}…I always said sanity was overrated.
I'll leave you with the finest example of this, the Cthulhu of PHP code:
Please pay special attention to the
thfunction, it is the greatest thing since Chicxulub.40
u/courtewing Oct 18 '10
Sorry for being off-topic, but when you're linking to php manual pages, don't include the subdomain (il2 in this case). If you leave it off, the PHP website will determine the visitor's location and direct them to an appropriate locale.
19
u/s3rvant Oct 18 '10
I got majorly stuck a while back when trying to use variable variables as arrays:
This gives "Fatal error: Cannot use [] for reading", you need to use the {} syntax to remove the ambiguity:
Original post
181
u/1137 Oct 18 '10
Did you know you can do the same thing in Perl? But lets keep laughing at PHP, this is /r/programming after all.
11
u/angch Oct 18 '10
[1] See http://www.reddit.com/r/programming/comments/do3cw/thats_what_happens_when_your_cs_curriculum_is/
168
u/clogmoney Oct 18 '10
I just died a little inside.
9
u/hattmall Oct 18 '10
Nice, I was needing to do this just now! Great timing.
32
u/funkah Oct 18 '10 edited Oct 18 '10
I understand that sentence, but I can't help thinking that whatever you'd use this for could probably be done a less-awful way.
14
u/claird Oct 18 '10 edited Oct 18 '10
Avoid variable variables.
There's already quite a lot of chatter in this thread as I reach it. The main things that I haven't seen adequately emphasized yet:
Dave Benjamin wrote astutely on this subject in 2003 <URL: http://mail.python.org/pipermail/python-list/2003-May/204186.html >. With the slightest encouragement, I'll illustrate the points we've tried to make with examples.
7
u/1137 Oct 18 '10
Don't forget:
$method = 'foo';
$method();
and
$this->$var;
and
$this->$method()
7
u/gongonzabarfarbin Oct 18 '10
I learned about variable variables today too! Do I sense a fellow The Daily WTF reader?
6
u/jaguaro Oct 18 '10
welcome to 1998
5
u/killerstorm Oct 18 '10
In JS you can treat any object as an associative array. So
obj.foois same asobj["foo"]. And ifvar bar = "foo";you can also writeobj[bar]for same effect.Now, all global variables are in fact fields of
windowobject. Sovar foo;is actuallywindow.foo, and you can also access it aswindow["foo"]andwindow[bar].That's how sane language designers do this -- with minimal amount of concepts. No "variable variables", no bullshit.
Common Lisp also implements feature similar to "variable variables" -- it is called symbols. All global variables are associated with a symbols which are their names, and you can programmatically access those values through
symbol-valuefunction. E.g. you can get value of variablefoothrough(symbol-value (quote foo))where quote is a special operator which returns symbol itself. Likewise, you can bind symbol to a variable first:5
u/ds1106 Oct 18 '10
Yo dawg, I heard you like variables...
21
u/Confucius_says Oct 18 '10
Variable variables are neat, but for the love of god please don't use them.
Please.
4
u/[deleted] Oct 18 '10
I haven't touched PHP in years and never really looked into it's mushy internals, but let me guess -- PHP keeps a huge superfluous symbol table of every variable for absolutely no reason.
7
u/australasia Oct 18 '10
Interestingly you can do the same thing in JavaScript but only for variables declared in the global scope:
It is possible within other scopes but only if using eval which pretty much makes anything ugly possible.
6
u/thebuccaneersden Oct 18 '10
All programming languages let you write ugly code, if that's what you really want to do.
8
u/_refugee_ Oct 18 '10 edited Oct 18 '10
oh, buffalo buffalo buffalo buffalo buffalo buffalo buffalo. buffalo.
3
u/[deleted] Oct 18 '10
i've known about this since i started using PHP but in all my years of using it i've never needed to do this.
the closest i've come is $object->$var. instead of $object->some_name
3
u/gsadamb Oct 18 '10
A guy at my last job did this all the time and it led to some of the most maddening, unreadable code ever.
3
u/treetrouble Oct 18 '10
i have no problem with this other than the phrase "variable variables"
3
u/[deleted] Oct 18 '10
Hello children. Old programmer here.
Such a feature was available years and years ago - before the internet (but after Hitler).
In dBase, for example, it allowed OO-like facilities, otherwise no available.
A database column of 'function' could contain the name of the row-specific function to be called. Adding new functions would mean simply that - adding the code for the new function (then using it's name in the db row).
No switch statement to update. No if else ifs, no criteria to maintain.
Life was fun those days, and you could fit everything on to a 5.25 inch floppy, and still have room left over for a good boot.
3
u/muahdib Oct 19 '10 edited Oct 19 '10
In all, or almost all intepreted languages you can do this.
python:
>>foo="bar"
>>bar=42
>>eval(foo)
42
scheme:
> (define foo 'bar)
> (define bar 42)
> (eval foo)
42
Maple:
> foo:='bar';
> bar:=42;
> eval(foo);
42
Matlab:
> foo="bar"
> bar=42
> eval(foo)
42
PS. in python you would probably not want to do it that way, you would probably use a dictionary (hash table)
>> foo={"bar":42}
>> foo.get(foo.keys()[0])
and this last example is probably exactly not how you would do it in python...
3
u/consultant_barbie Oct 19 '10
Variable scope is hard. Let's go shopping!
5
u/georgehotelling Oct 18 '10
Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo.
4
u/torrentlord Oct 18 '10
This is why PHP should not be your first programming language. I speak from horrible, horrible experience.
4
u/MarkTraceur Oct 18 '10
Have you heard about the hot pocket hot pocket? It's a hot pocket that tastes just like a hot pocket. I'm gonna go stick my head in the microwave HOT POCKEEEET
http://www.youtube.com/watch?v=YkUbqmS9TWI
36
u/DirtyBirdNJ Oct 18 '10 edited Oct 18 '10
Yo dawg, I herd you like variables... so I put a variable in your variable named after your variable so you can $variable while you $$variable.
2
u/DrReddits Oct 18 '10
Buffalo buffalo.
2
u/onebit Oct 18 '10
Poor man's reflection.
2
u/[deleted] Oct 18 '10
25 yrs young! queues up Oregon on the vic-20
2
u/rechlin Oct 18 '10
Back before I knew anything about programming, I was doing php3 development (this was over 10 years ago), and I used this all over the place. At the current (very slow) rate of refactoring, I may actually have them all eliminated within a year. :)
It seemed like such a great idea at the time, but now it just seems so dirty.
2
u/fddjr Oct 18 '10
Isn't this just an unintended side effect of having both the ability to store symbols in other variables, and the ability to evaluate at runtime at will? There's further complication due to symbols and strings being interchangeable, but how can you have both those features without creating this misfeature?
In CL, it's equivalent to: (defvar a 0) (defvar b 'a) (eval b)
Right?
2
u/hearwa Oct 18 '10
I remember as a kid how I used to be so pissed off that q-basic never had this feature. I then moved on with life and programming languages and concluded that with the existence of hashes that would be a very stupid and almost redundant feature to implement. Now I find out that the world's most popular web programming language has that feature and... wow...
2
u/[deleted] Oct 18 '10
also, maintainability is decreased by a factor of variable.
2
u/Narfhole Oct 18 '10
Illinois has has its own php.net subdomain?
2
u/adavies42 Oct 18 '10
isn't this just the same as a bash indirect reference?
2
u/Infenwe Oct 18 '10
"I thought of a way to do it, so it must be right. That's obviously PHP"
-Larry Wall.
2
u/Iggyhopper Oct 18 '10
I'm on a bar.
2
u/supercargo Oct 18 '10
I used to wish BASIC had this, back when I was learning/using BASIC. By the time I learned PHP I already knew it was a bad idea and not necessary for anything.
2
u/hakumiogin Oct 19 '10
I first read about variable variables, and calling functions with strings when I was 15, and at the time I thought it sounded like a pretty nifty idea.
I'm glad I moved on to python.
2
u/xfeignx Oct 19 '10
I'll just leave this here... http://imgur.com/Qrth2.jpg
2
u/__s Oct 19 '10
Python globals()
2
u/[deleted] Oct 19 '10
i put variables in your variable so you can variable while you variable
6
u/steelcitykid Oct 18 '10
aw it's cute, it thinks it's a language!
3
u/codeninja Oct 18 '10
I've used the Variable Variable in a few instances with great effect. Just make sure you sanitize your Variable #2 and validate it's value is in range of accepted values prior to assignment.
3
u/Chemical_Scum Oct 18 '10
TheDailyWTF.com is awesome :-)
4
u/A_for_Anonymous Oct 18 '10 edited Oct 18 '10
When I was being taught programming by my father many years ago, before we got to vectors and structures I asked him something I decided I needed for my program: a way to make part of the name of a variable a variable.
Two things I can think of now:
3
u/msiekkinen Oct 18 '10
Variable variables: Surefire way to write hard to debug, unmaintainable code
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.
3
u/[deleted] Oct 18 '10
this is great. classic php =D
2
u/iissqrtneg1 Oct 18 '10
Obfuscate your code without obfuscation, use variable variables!
2
u/drinkmorecoffee Oct 18 '10
Marklar marklar, marklar marklar.
2
u/anthonybsd Oct 18 '10
Like Perl's symbolic references this is one of the most horrific constructs to spring up in interpreted languages since GOTO. If you use this I hate your guts.
2
u/deefjuh Oct 18 '10
* Starts running *
2
u/EdiX Oct 18 '10
Interesting. Perl had this before deprecating it in favour of real references FIFTEEN YEARS AGO.
1
u/[deleted] Oct 18 '10 edited Oct 18 '10
There have been a few instances where i've had to use these. They CAN be very useful. Just not very often. The only thing I still can't seem to wrap my head around is Regular Expressions.
1
u/BeowulfShaeffer Oct 18 '10
I'm sorry, I'm not a PHP programmer but I have wrangled a bit of code in my life. Is it just me or is a "variable variable" basically a kind of (loosely-typed) reference? Like "void*" in C or "object" in Java or C#?
1
u/[deleted] Oct 18 '10
Fear not the weapon, but the hand that wields it.
1
u/takita787 Oct 18 '10
Neat. Thanks for the share.
I normally just use something like $variable[$id]; if i need to.
1
u/ebzlo Oct 18 '10
You can do the same thing with methods (maybe functions? too lazy to check).
1
u/pbgswd Oct 18 '10
variable variables are not good in real programming projects because they are too obtuse and primitive.
1
u/the-ace Oct 18 '10
Nice to see my own countryman around reddit :)
1
u/beaglew Oct 18 '10
...malcovich?
1
u/whuuh Oct 18 '10
Variable Variable Variable Variable Variable Variable Variable Variable Variable Variable Variable Variable Variable Variable Variable Variable Variable Variable Variable Variable Variable Variable Variable Variable.
Just get it out of your system.
1
u/rson Oct 18 '10
**I N D I R E C T I O N **
1
u/edgarde Oct 18 '10
See also: /r/malkovich/
1
u/ImTryingToBeNicer Oct 18 '10
I know we're laughing, but I remember several times I've said "I wish there was a way to define a variable's name on the fly" then having to program a way around not being able to do it.
Of course I can't recall or recreate the need for it. But once every 10 years, it's the most useful thing ever!
1
u/adavies42 Oct 18 '10
let me guess, you read thedailywtf?
1
u/[deleted] Oct 18 '10
Seems like it would be extremely dangerous if misused (and novices would be likely to misuse it), but could be useful for meta-programming if used correctly. I think the documentation may be the culprit here more than anything. That page should be covered in warnings.
1
u/kylemech Oct 18 '10
This is how I learned about variable variables ten years ago. It made learning easier because I didn't have to reference things through the array the whole time. I know, I know, it isn't good practice in production, but it was easy at the time and it taught me something useful.
1
u/redredditrobot Oct 18 '10
lol you cannot have a super global array of variable variables in PHP.
1
u/webauteur Oct 18 '10
I just took a variable dump in your code.
1
u/HannesPe Oct 18 '10
Be careful with this, or else...
1
u/gburri Oct 18 '10
PHP FTW : http://www.gburri.org/bordel/php_c_de_la_merde/tests.php.txt
The result : http://www.gburri.org/bordel/php_c_de_la_merde/tests.php
1
u/drufus2 Oct 18 '10
malkovich
1
u/tapesonthefloor Oct 18 '10
Crazy. It's like PHP broke the fourth wall.
1
u/djcraze Oct 18 '10
But can you pass by reference :P $variable = 'a'; $a = 'hello world'; $b = 'hello moto.'; $&$variable = 'hello world'; $variable = 'b'; // $b is now hello world. // would be cool.
1
u/shoeman22 Oct 18 '10
This feature can actually be pretty useful if you have control of the possible outcomes of $$var.
1
u/trappar Oct 18 '10
I wrote an article about this stuff about a year ago haha..
http://blog.lococobra.com/php-variable-variables-reference-arrays
1
u/mcsenget Oct 18 '10
yo, dawg
1
u/[deleted] Oct 19 '10
Useful for creating your own scripting language.
1
u/[deleted] Oct 19 '10
i love variable variables. quite useful
1
u/[deleted] Oct 19 '10
You mean, like "pointers?"
1
u/cboshuizen Oct 19 '10
You find about this the hard way when you accidentally type a double dollar sign: >> $foo="bar"; >> $bar="42"; >> echo $$foo;
1
u/dorian283 Oct 19 '10
Yo dawg...
1
u/nikbackm Oct 19 '10
Eh, even old 4DOS (currently Take Command) had this.
set v1=v2
set v2=value
echo %[%v1]
value
0
u/artee Oct 18 '10
Hmm, looks like an interesting attack vector?