为什么 PHP 中会出现“无法突破/继续 1 级”


Why does 'Cannot break/continue 1 level' comes in PHP?

我有时会在生产中遇到此错误:

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收到价值。

有谁知道 PHP 中什么时候会出现"无法突破/继续 1 级"?

我已经看到这篇文章PHP致命错误:无法中断/继续。但没有得到任何帮助。

你不能从 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';
?>

如果在函数中只是更改中断; 返回;

如果你仍然想从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++;
}

您也可以使用开关和默认值。

$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++;
}