冒着把自己归咎于骨头的风险,我仍然会问一个问题:在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 }
在一个函数中,我可以使用'fall through'模拟并在成功的情况下返回:
function xx {
if {... if {... if {... success; return; }}}
failure
}
..但在主程序?
PHP中没有andif
运算符,但您可以使用早期返回(或“失败快速”)习惯用法,并在测试失败时返回失败。这样,你不需要一堆else
s:
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
在一个logical operators语句中进行多次检查。例如 :
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这样的东西,我觉得唯一的办法就是 - 屏住呼吸:GOTO(抱歉破坏圣诞节......)
if ( ....) {
contact server ...
if ( ... ){
check ...
if ( ... ) {
success ;
goto success;
}}}
failure;
success:
continue...
在我看来,其他一切都变得更加复杂。