简体   繁体   English

如何退出if语句并继续执行else

[英]How to exit if statement and continue to else

This is a long shot question, but is there a way in php to exit an "if" statement and continue on to the "else" statement if an error occurs inside the if block? 这是一个长镜头问题,但是如果在if块中发生错误,那么在php中有一种方法可以退出“if”语句并继续执行“else”语句吗?

example

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

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

}

else 
{
//do method two
}

Of course it is possible to do a nested if inside the first if, but that seems hacky. 当然可以在第一个if内部进行嵌套,但这看起来很hacky。

TIA TIA

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

}

I would just use a function so you don't duplicate code: 我只是使用一个函数,所以你不重复代码:

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

function elsefunction() {
    //else code here
}

Should that be possible? 应该可以吗? Anyway you might consider changing it to. 无论如何,您可能会考虑将其更改为。

$error = "";
if ($condition == "good") {
 if (/*errorhappens*/) { $error = "somerror"; }
}
if (($condition != "good") || ($error != "") ) {
 //dostuff
}

You could modify methodOne() such that it returns true on success and false on error: 您可以修改methodOne() ,使其在成功时返回true ,在出错时返回false

if($condition == "good" && methodOne()){
  // Both $condition == "good" and methodOne() returned true
}else{
  // Either $condition != "good" or methodOne() returned false
}

Assuming that methodOne returns false on error : 假设methodOne在出错时返回false:

if !($condition == "good" && methodOne())
{
//do method two
}

you really need this? 你真的需要这个吗? i think no... but you can hack.. 我想不...但你可以破解..

do{

   $repeat = false;

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

    }    
    else 
    {
       //do method two
    }

}while( $ok ) ;

I advise on methods to separate... 我建议分开的方法......

I find using switches instead of if...else are handy for doing this: Omitting a break statement makes the switch fall through to the next case: 我发现使用开关而不是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.
}
if ($condition == "good") {
    try{
        method_1();
    }
    catch(Exception $e){
       method_2();
    }
} 
else {
    method_2();
}

function method_2(){
   //some statement
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM