donoworuq450547191 2014-11-26 23:04
浏览 46
已采纳

使用循环和数组定义PHP变量名 - 良好的做​​法? [关闭]

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?

  • 写回答

1条回答 默认 最新

  • doudouwd2017 2014-11-26 23:41
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题