[英]How to exit if statement and continue to else
這是一個長鏡頭問題,但是如果在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內部進行嵌套,但這看起來很hacky。
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.