【问题标题】:php andif statement, fall throughphp andif 语句,通过
【发布时间】:2017-12-23 08:54:15
【问题描述】:

冒着自责到骨子里的风险,我还是问这个问题: 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
}

.. 但在主程序中?

【问题讨论】:

  • 如果出现问题,您可以使用trycatch 抛出异常。

标签: php if-statement goto fall-through


【解决方案1】:

PHP 中没有 andif 运算符,但您可以使用 early-return(或“fail-fast”)习语,并在测试失败时返回失败。这样,你就不需要一堆elses:

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

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

    // Etc...

    return success;
}

【讨论】:

  • 如果在一个函数中你可以做一个''fall through''。见上文。
【解决方案2】:

我会先检查错误:

if (not_true) {
    return;
}

connect_server; 

if (second_not_true) {
    return;
}

check;

等等……

您还可以使用logical operators 在一个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...
}

【讨论】:

  • @user30424 你听说过&& 吗?
  • 关键是我想在第一次测试成功后立即联系服务器。我当然可以从服务器收集所有数据,然后使用 && 运算符。
  • 我明白了。 die() 而不是 return 呢?
  • 还是通过异常?
【解决方案3】:

好吧,由于 php 中没有 andif 之类的东西,我认为唯一的方法是 - 屏住呼吸: 去 (对不起,破坏了圣诞节……)

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

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

【讨论】:

    猜你喜欢
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    相关资源
    最近更新 更多