Recipe 5.4. Creating a Dynamic Variable Name5.4.1. ProblemYou want to construct 5.4.2. SolutionUse PHP's variable variable syntax by prepending a $animal = 'turtles'; 5.4.3. DiscussionPlacing two dollar signs before a variable name causes PHP to de-reference $animal = 'turtles'; This prints 103. Because $animal = 'turtles', $$animal is $turtles, which equals 103. Using curly braces $stooges = array('Moe','Larry','Curly'); PHP evaluates the expression between the curly braces and uses it as a variable name. That expression can even have function calls in it, such as Variable variables are also useful when iterating through similarly named variables. Say you are querying a database table that has fields named title_1, title_2, etc. If you want to check if a title matches any of those values, the easiest way is to loop through them like this: for ($i = 1; $i <= $n; $i++) { Of course, it would be more straightforward to store these values in an array, but if you are maintaining old code that uses this technique (and you can't change it), variable variables are helpful. The curly brace syntax is also necessary in resolving ambiguity about array elements. The variable variable $$donkeys[12] could have two meanings. The first is "take what's in the 12th element of the $donkeys array and use that as a variable name." Write this as: ${$donkeys[12]}. The second is "use what's in the scalar $donkeys as an array name and look in the 12th element of that array." Write this as: ${$donkeys}[12]. You are not limited by two dollar signs. You can use three, or more, but in practice it's rare to see greater than two levels of indirection. 5.4.4. See Alsohttp://www.php.net/language.variables.variable for documentation on variable variables. |
Tuesday, January 19, 2010
Recipe 5.4. Creating a Dynamic Variable Name
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment