Created
September 2, 2011 13:51
-
-
Save anonymous/1188637 to your computer and use it in GitHub Desktop.
PHP example on variable variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function myForm($a, $b, $c, $d) { | |
// .. suppose the function receives variables called a, b, c, d | |
foreach (array('a', 'b', 'c', 'd') as $key) { | |
$form[$key] = array( | |
'#type' => 'hidden', | |
'#value' => $$key, | |
); | |
} | |
// without variables variables you have to | |
$form['a'] = array( | |
'#type' => 'hidden', | |
'#value' => $a, | |
); | |
// and 3 more times | |
} | |
/* | |
This is real code I wrote once and I don't see anything wrong with it. | |
Can be solved without variable variables: | |
1) change function prototype (receive array of variables keyed by their names instead of list of arguments) | |
what if your function is called from 300 places and you really don't want to change it? | |
2) create another array keyed by variable names and use that in cycle | |
$tmp = array('a' => $a, 'b' => $b); | |
why should I create another copy of variables when I can solve it using native language features? | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment