这是一个很长的问题,但是如果在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内部进行嵌套,但这看起来很糟糕。
TIA
答案 0 :(得分: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
}
答案 1 :(得分:3)
我只是使用一个函数,所以你不要重复代码:
if ($condition == "good") {
//do method one
//error occurs during method one
if($error == true) {
elsefunction();
}
} else {
elsefunction();
}
function elsefunction() {
//else code here
}
答案 2 :(得分:1)
您可以修改methodOne()
,使其在成功时返回true
,在错误时返回false
:
if($condition == "good" && methodOne()){
// Both $condition == "good" and methodOne() returned true
}else{
// Either $condition != "good" or methodOne() returned false
}
答案 3 :(得分:1)
这可能吗? 无论如何,您可以考虑将其更改为。
$error = "";
if ($condition == "good") {
if (/*errorhappens*/) { $error = "somerror"; }
}
if (($condition != "good") || ($error != "") ) {
//dostuff
}
答案 4 :(得分:1)
假设methodOne在出错时返回false:
if !($condition == "good" && methodOne())
{
//do method two
}
答案 5 :(得分:0)
do{
$repeat = false;
if ($condition == "good")
{
//do method one
$condition = "bad";
$repeat = true;
}
else
{
//do method two
}
}while( $ok ) ;
我建议分开的方法......
答案 6 :(得分: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.
}
答案 7 :(得分:0)
if ($condition == "good") {
try{
method_1();
}
catch(Exception $e){
method_2();
}
}
else {
method_2();
}
function method_2(){
//some statement
}