Variable Variables

Indirectly referring to a variable.

 

Uses the value of a variable and treat that as the name of a variable.

 

<?php
	$myVar = 42 ;

	$foo = "myVar" ;

	echo "\$foo has a value of: " . $$foo . "<br>" ;

?>

Displays:

$foo has a value of: 42

 

 

Note the use of two $$ signs to reference the value in $myVar.

 

PHP uses the value in $foo (which in this case is myVar) and returns the value (42) in the variable of that name ($myVar)

 

Further indirection can be used but can also get confusing. Basically use another $ for each level of indirection used:

 

<?php
	$myVar = "Potato" ;

	$yourVar = "myVar" ;

	$theirVar = "yourVar" ;

	$herVar = "theirVar" ;

	$hisVar = "herVar" ;

	echo "\$myVar has a value of: " . $myVar . "<br>" ;

	echo "\$yourVar has a value of: " . $$yourVar . "<br>" ;

	echo "\$theirVar has a value of: " . $$$theirVar . "<br>" ;

	echo "\$herVar has a value of: " . $$$$herVar . "<br>" ;

	echo "\$hisVar has a value of: " . $$$$$hisVar . "<br>" ;
?>

Displays:

$myVar has a value of: Potato
$yourVar has a value of: Potato
$theirVar has a value of: Potato
$herVar has a value of: Potato
$hisVar has a value of: Potato

 

Leave a Reply