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

2022-08-30 19:09:43

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

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致命错误:无法中断/继续。但没有得到任何帮助。


答案 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

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


推荐