[英]php andif statement, fall through
冒着責怪自己的風險,我仍然會問一個問題:php中是否有類似“ andif”的東西,或者我該如何以一種優雅的方式解決以下問題?
場景:如果是真的,先進行測試,然后進行一些處理(例如,聯系服務器),然后進行第二次測試,再進行某些操作……進行第三次測試,然后再進行結果;或者-如果以上任何一項失敗,則始終輸出同樣的失敗。
而不是每次都重復else語句...
if ( ....) {
contact server ...
if ( ... ){
check ...
if ( ... ) {
success ;
} else { failure ... }
} else { failure ... }
} else { failure ... }
..我正在尋找類似的東西:
if ( ...) {
do something...
andif ( test ) {
do something more ...
andif ( test) {
do }
else {
collective error }
在一個函數中,如果成功,我可以使用“失敗”模擬並返回:
function xx {
if {... if {... if {... success; return; }}}
failure
}
..但是在主程序中?
PHP中沒有andif
運算符,但是您可以使用早期返回(或“快速失敗”)慣用語,並在測試失敗時返回失敗。 這樣,您不需要一堆else
:
function xx {
if (!test1) {
return failure;
}
someProcessing();
if (!test2) {
return failure;
}
// Etc...
return success;
}
我會先檢查錯誤:
if (not_true) {
return;
}
connect_server;
if (second_not_true) {
return;
}
check;
等等...
您也可以使用邏輯運算符在一個if
語句中進行多次檢入。 例如 :
if (test && second_test && third_test) { // means if test is true and if second_test is true and if third_test is true
// do the stuff if success...
} else {
// do the stuff if errors...
}
好吧,因為在php中沒有andif這樣的東西,所以我認為唯一的方法是-屏住呼吸:GOTO(抱歉破壞聖誕節...)
if ( ....) {
contact server ...
if ( ... ){
check ...
if ( ... ) {
success ;
goto success;
}}}
failure;
success:
continue...
在我看來,其他所有事情都更加復雜。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.