【问题标题】:Is there any possibility to break a loop while calling a function?调用函数时是否有可能打破循环?
【发布时间】:2014-09-15 12:56:33
【问题描述】:

假设我有一个简单的代码:

while(1) {
  myend();
}

function myend() {
  echo rand(0,10);
  echo "<br>";
  if(rand(0,10) < 3) break;
}

这不适用于错误代码“致命错误:无法在线中断/继续 1 级”。

那么在子函数执行期间是否有可能终止循环?

【问题讨论】:

标签: php loops


【解决方案1】:

使循环条件依赖于函数的返回值:

$continue = true;
while( $continue) {
    $continue = myend();
}

然后,将您的函数更改为:

function myend() {
  echo rand(0,10);
  echo "<br>";
  return (rand(0,10) < 3) ? false : true;
}

【讨论】:

  • 而是do {... } while(fun())。
  • myend 在我的情况下也将被评估。
【解决方案2】:

没有。不应该有;如果您的函数在您不在循环中的某处被调用,您的代码将停止死机。在上面的例子中,你的调用代码应该检查函数的返回,然后决定是否停止循环。例如:

while(1) {
  if (myend())
    break;
}

function myend() {
  echo rand(0,10);
  echo "<br>";
  return rand(0,10) < 3;
}

【讨论】:

    【解决方案3】:

    用途:

    $cond = true;
    while($cond) {
      $cond = myend();
    }
    
    function myend() {
      echo rand(0,10);
      echo "<br>";
      if(rand(0,10) < 3) return false;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      相关资源
      最近更新 更多