这是一个长期的问题,但是如果 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
这是一个长期的问题,但是如果 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
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
}
我只会使用一个函数,这样你就不会重复代码:
if ($condition == "good") {
//do method one
//error occurs during method one
if($error == true) {
elsefunction();
}
} else {
elsefunction();
}
function elsefunction() {
//else code here
}
这应该是可能的吗?无论如何,您可以考虑将其更改为。
$error = "";
if ($condition == "good") {
if (/*errorhappens*/) { $error = "somerror"; }
}
if (($condition != "good") || ($error != "") ) {
//dostuff
}
您可以进行修改methodOne()
,使其true
在成功和false
错误时返回:
if($condition == "good" && methodOne()){
// Both $condition == "good" and methodOne() returned true
}else{
// Either $condition != "good" or methodOne() returned false
}
假设 methodOne 在错误时返回 false :
if !($condition == "good" && methodOne())
{
//do method two
}
你真的需要这个吗?我认为不...但你可以破解..
do{
$repeat = false;
if ($condition == "good")
{
//do method one
$condition = "bad";
$repeat = true;
}
else
{
//do method two
}
}while( $ok ) ;
我建议分离的方法...
我发现使用开关而不是 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
}