【问题标题】:Nested IF conditions with multiple logic operators (AND, OR)具有多个逻辑运算符(AND、OR)的嵌套 IF 条件
【发布时间】:2018-10-29 22:40:08
【问题描述】:

这是我在 stackoverflow 上的第一个问题,希望有人,在我旁边,需要这种类型的代码。

我编写的代码运行良好,但我想知道如何改进它,或者是否有更好的方法来实现相同的结果。

// Do NOT include files for '404' and pages 'abc' or 'def' with slug '123'
if (  $pageName !== '404'  ) 
{ 

    if (( $pageName == 'abc' ) && ( $pageSlug == '123' ) 
             OR ( $pageName == 'def' ) && ( $pageSlug == '123' )) {

        return NULL;

    }

    else {

        // include file
        require_once ( '/file.php' );

        // Do NOT include for page 'def'
        if ( $pageName !== 'def' ) {

            // include file
            require_once ( file_2.php' );

        }

    }

};

【问题讨论】:

  • 由于代码有效,不属于这里。你应该在代码审查时发帖。
  • 你可以做这个小的简化:if (( $pageName == 'abc' || $pageName == 'def') && $pageSlug == '123' )。如您所知,&& 优先于 ||,因此您可以使用括号覆盖它。
  • 感谢您的简化。代码更易读。

标签: php if-statement optimization logical-operators


【解决方案1】:

既然你已经在一个函数中,你可以通过立即返回 404 来减少一些嵌套。此外,由于“返回 NULL”,所以不需要 else,我认为打破你的 if -or into 2 ifs 使其更具可读性:

function your_func_name($pageName, $pageSlug) {
   if ( $pageName == '404' ) {
       return;
   }

   if ( $pageName == 'abc' && $pageSlug == '123' ) {
      return NULL;
   }

   if ( $pageName == 'def' && $pageSlug == '123' ) {
      return NULL;
   }

   // include file
   require_once ( '/file.php' );

   // Do NOT include for page 'def'
   if ( $pageName !== 'def' ) {
      // include file
      require_once ( 'file_2.php' );
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 1970-01-01
    相关资源
    最近更新 更多