[英]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.