简体   繁体   English

php andif语句,失败了

[英]php andif statement, fall through

With the risk to blame myself to the bones, I still ask the question: Is there anything like "andif" in php or how could I solve the below in an elegant way? 冒着责怪自己的风险,我仍然会问一个问题:php中是否有类似“ andif”的东西,或者我该如何以一种优雅的方式解决以下问题?

Scenario: First test, if true, do some processing (eg contact server), then have a second test, do something ... have third test, and then do the result or -- if any of the above fail -- always output the same failure. 场景:如果是真的,先进行测试,然后进行一些处理(例如,联系服务器),然后进行第二次测试,再进行某些操作……进行第三次测试,然后再进行结果;或者-如果以上任何一项失败,则始终输出同样的失败。

Instead of repeating the else statement every time ... 而不是每次都重复else语句...

if ( ....) { 
        contact server ...
        if (  ...  ){
        check ...       
            if (  ... )   {
                success  ;
            } else {  failure ...       }
        } else {  failure ...       }
} else {  failure ...       }

.. I look for something like that: ..我正在寻找类似的东西:

if ( ...) {
   do something...
   andif ( test ) {
      do something more ...
      andif ( test) {
         do }
else { 
   collective error }

In a function I can use a 'fall through' simulation with return in case of success: 在一个函数中,如果成功,我可以使用“失败”模拟并返回:

function xx {
 if {... if {... if {...  success; return; }}}
 failure
}

.. but in the main program? ..但是在主程序中?

There's no andif operator in PHP, but you could use the early-return (or "fail-fast") idiom, and return the failure whenever a test fails. PHP中没有andif运算符,但是您可以使用早期返回(或“快速失败”)惯用语,并在测试失败时返回失败。 That way, you don't need a bunch of else s: 这样,您不需要一堆else

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

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

    // Etc...

    return success;
}

I would check for error first : 我会先检查错误:

if (not_true) {
    return;
}

connect_server; 

if (second_not_true) {
    return;
}

check;

And so on... 等等...

You could also do multiple check in one if statement with logical operators . 您也可以使用逻辑运算符在一个if语句中进行多次检入。 For example : 例如 :

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

well, as there is no such thing as andif in php, I think the only way to do it is - hold your breath: GOTO (sorry for spoiling xmas ...) 好吧,因为在php中没有andif这样的东西,所以我认为唯一的方法是-屏住呼吸:GOTO(抱歉破坏圣诞节...)

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

everything else seems to me be more complicated. 在我看来,其他所有事情都更加复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM