3

这是一个长期的问题,但是如果 if 块内发生错误,php 中有没有办法退出“if”语句并继续执行“else”语句?

例子

if ($condition == "good")
{
//do method one

//error occurs during method one, need to exit and continue to else 

}

else 
{
//do method two
}

当然,可以在第一个 if 中做一个嵌套 if,但这似乎很老套。

TIA

4

8 回答 8

7
try {
    //do method one

    //error occurs during method one, need to exit and continue to else 
    if ($condition != "good") {
        throw new Exception('foo');
    }
} catch (Exception $e) {
    //do method two

}
于 2013-08-28T21:15:00.767 回答
3

我只会使用一个函数,这样你就不会重复代码:

if ($condition == "good") {
    //do method one
    //error occurs during method one
    if($error == true) {
        elsefunction();
    }
} else {
    elsefunction();
}

function elsefunction() {
    //else code here
}
于 2013-08-28T21:15:18.073 回答
2

这应该是可能的吗?无论如何,您可以考虑将其更改为。

$error = "";
if ($condition == "good") {
 if (/*errorhappens*/) { $error = "somerror"; }
}
if (($condition != "good") || ($error != "") ) {
 //dostuff
}
于 2013-08-28T21:17:38.300 回答
1

您可以进行修改methodOne(),使其true在成功和false错误时返回:

if($condition == "good" && methodOne()){
  // Both $condition == "good" and methodOne() returned true
}else{
  // Either $condition != "good" or methodOne() returned false
}
于 2013-08-28T21:15:44.507 回答
1

假设 methodOne 在错误时返回 false :

if !($condition == "good" && methodOne())
{
//do method two
}
于 2013-08-28T21:20:48.893 回答
0

你真的需要这个吗?我认为不...但你可以破解..

do{

   $repeat = false;

   if ($condition == "good")
   {
      //do method one
      $condition = "bad";
      $repeat = true;

    }    
    else 
    {
       //do method two
    }

}while( $ok ) ;

我建议分离的方法...

于 2013-08-28T21:25:54.023 回答
0

我发现使用开关而不是 if...else 这样做很方便:省略一个 break 语句会使开关落入下一个案例:

switch ($condition) {
case 'good':
    try {
        // method to handle good case.
        break;
    }
    catch (Exception $e) {
        // method to handle exception
        // No break, so switch continues to default case.
    }
default:
    // 'else' method
    // got here if condition wasn't good, or good method failed.
}
于 2015-11-10T12:02:54.147 回答
0
if ($condition == "good") {
    try{
        method_1();
    }
    catch(Exception $e){
       method_2();
    }
} 
else {
    method_2();
}

function method_2(){
   //some statement
}
于 2017-12-05T09:56:57.077 回答