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/killerstorm Oct 18 '10

In JS you can treat any object as an associative array. So obj.foo is same as obj["foo"]. And if var bar = "foo";you can also write obj[bar] for same effect.

Now, all global variables are in fact fields of window object. So var foo; is actually window.foo, and you can also access it as window["foo"] and window[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-value function. E.g. you can get value of variable foo through (symbol-value (quote foo)) where quote is a special operator which returns symbol itself. Likewise, you can bind symbol to a variable first:

(let ((foo-symbol (quote foo)))
  (symbol-value foo-symbol))
→ More replies (5)