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 三菱伺服电机按启动按钮有使能但不动作
  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号