简体   繁体   中英

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?

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

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. That way, you don't need a bunch of else s:

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

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

everything else seems to me be more complicated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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