douzhong6480 2014-06-10 14:39
浏览 62
已采纳

PHP是否有非短路比较运算符?

I recently came across a bug in some code at work where a series of function calls were aggregated into a single success condition. Something like

$success = true;
foreach($foo as $f) {
   $success = $success && do_foo($f);
}

The bug is do_foo() was intended to run across the entire collection (it has side-effects). but the && operator short-circuts and once once a false is encountered do_foo isn't called on the remainder of the collection. Easy enough to refactor, but it led me to wondering:

Does PHP have a logical operator that does not short-circut?

Edit: Let me be clear, I'm not asking how to solve the bug. This is a hypothetical question about syntax.

  • 写回答

2条回答 默认 最新

  • dongsu1539 2014-06-10 14:54
    关注

    There's no dedicated operator for this purpose, but you have the choice of doing whacky stuff like this (assuming do_foo($f) always returns a boolean:

    $success &= do_foo($f);
    

    The outcome will be a numeric 0 or 1 instead of a boolean, but when used in a condition it shouldn't matter.

    If the function doesn't always return a boolean or if the above is too unsettling:

    $success = (bool)($success & do_foo($f));
    

    Recommendation

    That said, do_foo($f) should be run unconditionally and its return value used in the next statement.

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

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳