【问题标题】:Why does 'Cannot break/continue 1 level' comes in PHP?为什么“不能中断/继续 1 级”出现在 PHP 中?
【发布时间】:2012-08-12 20:50:41
【问题描述】:

我有时会在以下位置收到此错误:

if( true == $objWebsite ) {
    $arrobjProperties = (array) $objWebsite->fetchProperties( );
    if( false == array_key_exists( $Id, $Properties ) ) {
       break;
    }
    $strBaseName = $strPortalSuffix . '/';

    return $strBaseName;
}

$strBaseName = $strSuffix ;
return $strBaseName;

我已尝试重现此问题。但没有取得任何进展。 $Id, $Properties 具有收到的价值。

有谁知道“不能中断/继续 1 级”何时出现在 PHP 中?

我看过这个帖子PHP Fatal error: Cannot break/continue。但没有得到任何帮助。

【问题讨论】:

  • 您认为break 在这种情况下的表现如何?
  • 周围的代码是什么? break 仅在循环或开关的上下文中使用。
  • 当不在循环内使用 break 或 continue 时会发生这种情况。这是我看到此错误的唯一原因。
  • 在这种情况下,false 和来自array_key_existsfalse 将松散匹配。小心松散的支票。 php.net/manual/en/language.operators.comparison.php
  • @SiGanteng:这部分属于函数。它在某些情况下有效,但在某些情况下会出错。所以我需要修改条件是否正确?

标签: php if-statement fatal-error


【解决方案1】:

你不能从 if 语句中“中断”。您只能从循环中中断。

如果你想用它来打破调用函数中的循环,你需要通过返回值来处理——或者抛出一个异常。


返回值方法:

while (MyLoop) {
   $strSecureBaseName = mySubFunction();
   if ($strSecureBaseName === false) {   // Note the triple equals sign.
        break;
   }
   // Use $strSecureBaseName;
}

// Function mySubFunction() returns the name, or false if not found.

使用异常 - 这里是漂亮的例子:http://php.net/manual/en/language.exceptions.php

<?php
function inverse($x) {
    if (!$x) {
        throw new \Exception('Division by zero.');
    } else {
        return 1/$x;
    }
}

try {
    echo inverse(5) . "\n";
    echo inverse(0) . "\n";
} catch (\Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>

【讨论】:

    【解决方案2】:

    如果在一个函数中只是改变 break;返回;

    【讨论】:

    • 为什么要退货?如果在if 之后有 0 条语句要执行,那么我们可以返回。但是如果有些语句需要执行,那么我们就不应该返回。
    • 我同意这种情况。它还取决于代码块尝试应用的逻辑。雅所以并不总是回来。
    【解决方案3】:

    如果你还想脱离if,可以使用while(true)

    例如

    $count = 0;
    if($a==$b){
        while(true){
            if($b==$c){
                $count = $count + 3;
                break;  // By this break you will be going out of while loop and execute remaining code of $count++.
            }
            $count = $count + 5;  //
            break;  
        }
        $count++;
    }
    

    你也可以使用 switch 和 default。

    $count = 0;
    if($a==$b){
        switch(true){
          default:  
             if($b==$c){
                $count = $count + 3;
                break;  // By this break you will be going out of switch and execute remaining code of $count++.  
            }
            $count = $count + 5;  //
        }
        $count++;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      • 2019-11-02
      相关资源
      最近更新 更多