dongxin0031 2009-01-07 08:41
浏览 9
已采纳

你认为foreach((数组)$ foo为$ bar)代码味道?

Do you consider this a code smell?

foreach((array)$foo as $bar)
{
    $bar->doStuff();
}

Should i use that instead?

if (isset($foo) && is_array($foo))
{
    foreach($foo as $bar)
    {
        $bar->doStuff();
    }
}

Any other good practices to cover not set variables and assert an array?

  • 写回答

8条回答 默认 最新

  • doupijin0397 2009-01-07 09:12
    关注

    They're both code smells. The second one is just evading all the error messages, kind of like turning off the fire alarm before you set your kitchen on fire. Both of those tell you that you have no idea what's in the variable $foo or if it's even been defined in the code above. You need to go back up through the code and find out exactly what's going on with $foo.

    If it was my code, $foo would probably be always defined either as an array, or else false to indicate the array isn't needed:

    if(do_we_need_an_array())
      $foo = function_returning_an_array();
    else
      $foo = false;
    
    [...snip...]
    
    if($foo)
      foreach($foo as $f) { ... }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动