Loading ...
Sorry, an error occurred while loading the content.

Dynamic Variable Magic PHP

Expand Messages
  • Day Dreamer
    Dynamic variable is PHP s one trickiest part of coding which reduce some short of work if you can implement it. Lets have a closer look. Use PHP s variable
    Message 1 of 1 , Nov 1, 2004
    • 0 Attachment
      Dynamic variable is PHP's one trickiest part of coding which reduce
      some short of work if you can implement it. Lets have a closer look.

      Use PHP's variable variable syntax by prepending a $ to a variable
      whose value is the variable name you want:

      $animal = 'turtles';
      $turtles = 103;
      print $$animal;
      103

      Discussion:
      The previous example prints 103. Because $animal = 'turtles', $$animal
      is $turtles, which equals 103. Using curly braces, you can construct
      more complicated expressions that indicate variable names:

      $stooges = array('Moe','Larry','Curly');
      $stooge_moe = 'Moses Horwitz';
      $stooge_larry = 'Louis Feinberg';
      $stooge_curly = 'Jerome Horwitz';
      foreach ($stooges as $s) {
      print "$s's real name was ${'stooge_'.strtolower($s)}.\n";}

      Moe's real name was Moses Horwitz.
      Larry's real name was Louis Feinberg.
      Curly's real name was Jerome Horwitz.

      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 strtolower( ). 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++) {
      $t = "title_$i";
      if ($title == $$t) { /* match */ }
      }

      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 the12th 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].

      For furteher study see http://www.php.net/language.variables.variable
      for documentation on variable variables.
    Your message has been successfully submitted and would be delivered to recipients shortly.