dongyan3562 2011-06-15 04:15
浏览 218
已采纳

访问PHP foreach循环外的变量

In some code I'm working on I have noticed that several variables are being accessed from outside of foreach loops.

This is seen in codeigniter view files of this particular app.

For example, a view file:

<?php
foreach ($items as $row):
endforeach;

// HTML / PHP code...

 <td>
     <?php echo form_checkbox('option_1','1', FALSE); ?>
     <?php echo form_hidden('weight_unit', $row->weight_unit); ?>
 </td>
// etc...

This works (ie, no errors) but I wonder if this would be considered a bad practice and if so, why? (scope, etc)

Does anyone have an opinion on this and should variables only be called inside their corresponding loops?

Another issue I've noticed is if a variable is required in several parts of a view file: should I refactor to have multiple loops or should there be a single foreach / endforeach and the begin / end of the file.

Any suggestions are much appreciated. Thanks.

  • 写回答

4条回答 默认 最新

  • dongshuao2309 2011-06-15 04:21
    关注

    $row will be the last item in the array, or unset, when it reaches your other code.

    Is that want you want? If so, then it's not bad practice, per se. But you should at least document that the behavior is intended, because it's not intuitive.

    Better practice is something like:

    foreach ($foo as $bar) 
    {
      // do something
    }
    $last_bar = isset($bar) ? $bar : null;
    

    There it's obvious that you mean to do something with $last_bar.

    Another issue I've noticed is if a variable is required in several parts of a view file

    If you must iterate over your loop in different places in your view, then that's okay.

    But if you just need a certain piece of information deep inside some array, then you should stick it into an easily accessible variable and use that instead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)