【问题标题】:php return statement in if statementif语句中的php返回语句
【发布时间】:2015-07-28 11:20:48
【问题描述】:

也许我的问题有点初级或愚蠢,但我需要验证这一点。

我有一个 php 函数“functionA”,它在 for 循环中被重复调用:

...
for($j=0; $j<$n_samples;$j++) {
    if($type=='triband') {
        functionA($arg1,$arg2);                 
    }
}
...

和我的函数A:

...
functionA($arg1,$arg2) {
    $wide_avg_txon = substr($bit_sequence,0,1);
    if($wide_avg_txon==0)
    {
        echo " ---> is OFF...<br />";
    }
    else
    {
        echo " ---> is ON...<br />";
        // if is ON then skip execution of code inside the function
        return;
    }

    // DO SOME STUFF!
}
...

所以我不想执行 functionA 中的其余代码 if "$wide_avg_txon==1" 我只想继续执行 for 循环以进行下一次迭代!

上面的代码可以工作吗? 'return' 和 'return false' 之间有什么区别? 'return false' 是否也会起作用:

...
if($wide_avg_txon==0)
    {
        echo " ---> is OFF...<br />";
    }
    else
    {
        echo " ---> is ON...<br />";
        // if is ON then skip execution of code inside the function
        return false;
    }

谢谢!

【问题讨论】:

  • 两者都可以。如果你想以某种方式依赖它,你可以返回一些东西,例如if (functionA($arg1,$arg2 == )) {}
  • 如果您有任何需要,请发送至return true for on,因为true == 1

标签: php if-statement return


【解决方案1】:

您的 functionA 可以完美运行,但为了便于阅读,最好采用这种格式:

...
function functionA($arg1, $arg2) {

    $wide_avg_txon = substr($bit_sequence,0,1);

    // if is ON then skip execution of code inside this function
    if ($wide_avg_txon != 0) {
        echo " ---> is ON...<br />";
        return;
    }

    echo " ---> is OFF...<br />";

    // DO SOME STUFF!
}
...

不同的是,你立即取消不想要的“ON”条件,并尽快退出该功能。然后该函数的其余部分将处理您想做的任何事情,而不是坐在 if 语句块内。

【讨论】:

    【解决方案2】:

    return false 返回 false,一个布尔值。 return 将返回 NULL。两者都不会执行任何后续代码。

    因此,为了扩展 RST 的答案,两个返回都不满足 if 条件:

    if(functionA($arg1,$arg2))
         echo'foo';
    else
         echo'bar';
    

    bar 将被回显。

    这可能有用的地方是:

    $return=functionA($arg1,$arg2);
    if($return===NULL)
        echo'Nothing happened';
    elseif($return===false)
        echo'Something happened and it was false';
    else
        echo'Something happened and it was true';
    

    NULL 非常有用。

    【讨论】:

      【解决方案3】:

      函数将在 return 语句之后停止。您可以在此处阅读更多信息: http://php.net/manual/tr/function.return.php

      作为示例,您可以执行以下操作来测试:

      <?php
      $_SESSION['a'] = "Naber";
      function a(){
              return;
              unset($_SESSION['a']);
      }
      a(); // Let see that is session unset?
      echo $_SESSION['a'];
      ?>
      

      谢谢

      【讨论】:

        【解决方案4】:

        您的return 将起作用,因为您对返回的结果不感兴趣。你只想继续 for 循环。

        如果您有一个测试某些内容的代码构造,并且您想知道测试结果,那么您可以使用return false 让其余代码知道测试失败。

        【讨论】:

          猜你喜欢
          • 2023-02-21
          • 1970-01-01
          • 2020-08-09
          • 2020-07-30
          • 1970-01-01
          • 2018-05-07
          • 2021-08-31
          • 2018-04-18
          相关资源
          最近更新 更多