Variable name consist of variable in PHP

In certain situation we need to create a variable with name based on value of other variables. In many programming language it is not possible but with PHP it’s possible

$id = 5;
$post_5 = "My Text"; 				// For retriving value
$var_name = 'post_' . $id; 			// Generate variable name
$var = ${$var_name};				// use variable name
echo $var;							//My Text

Even we can use this in OOPS, such as field(property) name.

$var = $this->{$var_name};			// using this
echo $var;							 //My Text

Leave a Reply

Your email address will not be published. Required fields are marked *