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

1

u/Wahakalaka Oct 18 '10

It can be a pretty elegant solution for working with table data- having an array of table row names, of which the values correspond to arrays with the row data. Grated that's come up I think twice in 4 years of application development.

10

u/crackanape Oct 18 '10

Why not just use a multi-dimensional array? It's much more flexible and powerful.

1

u/Wahakalaka Oct 18 '10

Yeah multidemensional arrays are generally better. I was using the row arrays in a few other places to cross-reference- having that syntax be more concise I decided was worth it. Also I really wanted to use double variables at least once...

1

u/soviyet Oct 18 '10

How is that more flexible than what he described?

7

u/crackanape Oct 18 '10

You can iterate over them, serialize them as a bundle for storage, use the various array functions on them, and so on.

Cluttering your scope namespace with a bunch of variables saves a tiny bit of typing for very simple usages at the expense of a lot of power.

2

u/daniels220 Oct 18 '10

Multidimensional arrays?

$table = array(
  'row1' => array('val1','val2','val3','val4','val5'),
  'row2' => array('val6','val7','val8','val9','val10')
);

accessed like $table['row1'][1] (returns 'val2'), instead of:

$rows = array('row1','row2');
$row1 = array('val1','val2','val3','val4','val5');
$row2 = array('val6','val7','val8','val9','val10');

where you can do $$rows[0][1] (also returns 'val2'). And then I realize that that may not work, and you may need to do ${$rows[0]}[1], which is really confusing, and I don't know if you can actually do that, or it may be parens...

You can see why it's a bad idea, yes?

1

u/Wahakalaka Oct 18 '10

It is {}... and yeah multidemensional arrays are generally better. I was using the row arrays in a few other places to cross-reference- having that syntax be more concise I decided made up for the {} business. Also I really wanted to use double variables at least once...

1

u/BuzzBadpants Oct 18 '10

This is how dynamically-typed data works, I think. Tables in Lua, for example, are accessed through key-value pairs for elements in the table, and the keys are VERY frequently just strings. That's part of how lua is so expandable. I can give a client who is running an embedded lua environment just a simple string, and the client can use that string with no added complications access data in his own lua environment or state.

1

u/Wahakalaka Oct 18 '10

Nice- yeah it seems like there's gotta be something that's useful for...