Using PHP Dynamic Variables
PHP dynamic variables have a lot of usefulness. As you're programming for the web, you'll come across many cases where you have a block of code that you will want to use for a number of different cases. This is very common when you have output or validation helpers.
In this quick howto, I will show you how to use PHP's dynamic variables to create a basic little text output helper function. The example is simple, but the ability to do this comes in extremely handy as you start working on bigger projects.
First, let's define two arrays of information, one about my car and one about my favorite guitar:
'Saturn','model'=>'Vue');
$guitardata = array('make'=>'Heritage','model'=>'H-535');
Now that this data is set, we can create a function to put together our text output.
function buildAboutMe($data,$verb){
global ${$data.'data'}; // Bring the array within scope
$info = ${$data.'data'}; // Store the array as $info
return "I $verb a {$info['make']} {$info['model']}.";
}
In this function, we are passing in the $data parameter as a string. The function then uses a dynamic variable to bring the corresponding array within scope of the function. If we pass in 'myinfo', this would be the same as declaring
global $myinfodata
Then we store the $myinfodata array as that same value and access it when putting the string together. Simple enough!
The final code is the actual function calls, passing in a verb argument to make our output make sense based on what we're describing.
$car = buildAboutMe('car','drive');
echo $car; // I drive a Saturn Vue.
$guitar = buildAboutMe('guitar','play');
echo $guitar; // I play a Heritage H-535.
And that's all there is to it! This is a pretty basic example but you can imagine what kind of door using dynamic variables can open as you are writing your next web application!


