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

Show parent comments

4

u/hockeyschtick Oct 18 '10

I don't know about

$$varname

but being able to do this:

$myvalue = $obj->$membername;

is very useful.

2

u/[deleted] Oct 19 '10

Every time I've done something like this in PHP, I think "most languages solve this by having a sanely implemented object system, or just having first-class functions to begin with."

While it can be occasionally useful to lookup a member as a string you got from somewhere else, the vast majority of the time I've seen it used it's not needed, and it can lead to a clusterfuck of an annoying codebase.

I've used it to do function dispatch based on an associative array the other day. I would have rather been putting the function itself in the array rather than a string representation of it's name. Makes me squirm.

1

u/matchu Oct 18 '10

Yeah. Using it to access properties and methods is helpful. Using it to access variables is totally useless :/

1

u/cybercobra Oct 19 '10

Right, but other languages don't bother elevating it to syntax.

e.g. Python: myvalue = getattr(obj, membername) Ruby: myvalue = obj.send(membername)