Variable variables in PHP
Usually, variables are accessed using a fixed name. But in PHP it is also possible to make the name of the variable dependent on another variable, a function, or a constant. If the content of another variable is to be used as the variable name, it is sufficient to write a second dollar sign in front of the variable, otherwise, you have to use curly brackets.
Example: Make the variable name dependent on another variable
The following example shows how $var2 can be accessed without writing $var2 directly:
<?php // Set sample variables // note: $var1 contains the name of $var2 $var1 = 'var2'; $var2 = 'example'; // Display the variables var_dump($var1); var_dump($var2); // Variable variable name // $var1 becomes $var2 (since $var1 contains the string 'var2') var_dump($var1); ?>
Output:
string(4) "var2" string(7) "example" string(7) "example"
[st_adsense]
Example: Make the variable name dependent on a constant, an array value or a function
The name of the variable can also be taken from other sources. Then, however, the use of curly brackets in the form ${source} is necessary.
<?php $var2 = 'example'; var_dump($var2); // Source is a constant define('CONSTANT', 'var2'); var_dump( ${CONSTANT} ); // Source is an array value $tmp = array(0 => 'var2'); var_dump( ${$tmp[0]} ); // Source is a function function example() { return 'var2'; } var_dump( ${example()} ); ?>
Output:
string(7) "example" string(7) "example" string(7) "example" string(7) "example"
Example: Define the variable name even more indirectly
The variable generation of the variable name can be indirect as desired. So you are not limited to two dollar signs, but you can use more. If you want to make your own code as illegible as possible, you can follow the next example, in which $var1 refers to $var2, $var2 again to $var3, $var3 to $var4 and only $var4 contains the actual value.
<?php $var1 = 'var2'; $var2 = 'var3'; $var3 = 'var4'; $var4 = 'end'; var_dump($var1, $var2, $var3, $var4); echo('$var1: ' . $var1 ." \n"); echo('$var1: ' . $var1 ." \n"); echo('$var1: ' . $var1 ." \n"); echo('$var1: ' . $var1 ." \n"); ?>
Output:
string(4) "var2" string(4) "var3" string(4) "var4" string(3) "end" $var1: var2[st_adsense]$
$var1: var3$
$
$var1: var4$
$
$
$var1: end