November 27th, 2008 at 12:53 pm

Dynamic variables

What is a dynamic variable, or a variable variable, as they are sometimes called? When you create a variable, you give it a name. Consider this PHP example:

PHP:
  1. <?php
  2.    $foo = 'test';
  3.    echo $foo;
  4. ?>

The first line will create the variable $foo and assign the string value 'test' to it. In the second line, the content of the variable $foo will be printed. So far, nothing exciting. But now consider this:

PHP:
  1. <?php
  2.    $bar = 'foo';
  3.    $$bar = 'test';
  4.    echo $foo.$bar;
  5. ?>

(Note the double $ sign at the beginning of the second line.) What happens here? First, the value 'foo' is assigned to the variable bar. In the second line, a variable is created, and this variable's name will be the content of the variable $bar. This means, the variable $foo is created. Hence, the third line will output testfoo. You can also have dynamic variables in arrays and objects, even as function aliases:

PHP:
  1. <?php
  2.    $foobar = $foo[$bar];
  3.    $foobar = $foo->$bar;
  4.    
  5.    // want to match case sensitive or not?
  6.    $stripos_func = ($casesensitive) ? 'strpos' : 'stripos';
  7.    var_dump( $stripos_func('ABC', 'ab') ); // true if $casesensitive==false
  8. ?>

Leave a Comment