I need to define a set of variables to a series
$charta ='<img src="'.$_SERVER["DOCUMENT_ROOT"].'/output/pdf/charts/aplha.png" alt ="" />';
$chartb ='<img src="'.$_SERVER["DOCUMENT_ROOT"].'/output/pdf/charts/bravo.png" alt ="" />';
$chartc ='<img src="'.$_SERVER["DOCUMENT_ROOT"].'/output/pdf/charts/charlie.png" alt ="" />';
etc ...
Rather than define them all like this I want to use a loop to define them using an array
$names = array (
'aplha' => 'a',
'bravo' => 'b',
'charlie' => 'c'
);
So I tried this, after reading about variable variables in the PHP documentation
foreach($names as $k=>$v){
${'chart' . $v} ='<img src="'.$_SERVER["DOCUMENT_ROOT"].'/output/pdf/charts/'.$k.'.png" alt ="" />';
}
And this works.
My simple question is - is this good / acceptable practice? I explained my method to a more experienced programmer and they told me to find another way that didn't include variable variables, because they are bad practice - but I can't think of what's wrong with this, nor how to do it better.
Thoughts?
I would use an array with the $v being the key. It's readable. Even better:
$names = array(
'a' => 'yourimage1',
'b' => 'yourimage2',
'c' => 'yourimage3',
);
function chartImage($img_string = 'your-default-img')
{
return '<img src="'.$_SERVER["DOCUMENT_ROOT"].'/output/pdf/charts/'.$img_string.'.png" alt ="" />';
}
// somewhere in your code
print chartImage($names['a']); // or
<?= chartImage($names['a']); ?>
I would do it this way because it's easy to see what you are doing. Better readability.
Variable variables are bad practice when you have defined data. There's no reason to use it. Variable variables are used when you are dealing with data that is unknown. Since you know and predefine variables in a sequence, variable variables adds not enhancements and can make it very confusing to a second set of eyes when viewing the code.
A good example of using variable variables is in surveys. You're not sure how many validations there will be or answers and so you would code variables that hold variables data. When I created a survey system, I created variables that held variable data of arrays working on the validation types and input types. It comes down to context and fixing a solution. Using variable variables in your context is not fixing a solution.