php andif声明,通过

问题描述 投票:1回答:3

冒着把自己归咎于骨头的风险,我仍然会问一个问题:在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 if-statement goto fall-through
3个回答
0
投票

PHP中没有andif运算符,但您可以使用早期返回(或“失败快速”)习惯用法,并在测试失败时返回失败。这样,你不需要一堆elses:

function xx {
    if (!test1) {
        return failure;
    }

    someProcessing();
    if (!test2) {
        return failure;
    }

    // Etc...

    return success;
}

0
投票

我会先检查错误:

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...
}

0
投票

好吧,因为没有像php这样的东西,我觉得唯一的办法就是 - 屏住呼吸:GOTO(抱歉破坏圣诞节......)

   if  ( ....) { 
            contact server ...
            if (  ...  ){
            check ...       
                if (  ... )   {
                    success  ;
                    goto success;
                 }}}
    failure;
    success:
    continue...

在我看来,其他一切都变得更加复杂。

© www.soinside.com 2019 - 2024. All rights reserved.