【问题标题】:Why after continue; execution further function code is executed?为什么要继续;执行进一步的功能代码被执行?
【发布时间】:2019-05-27 05:20:19
【问题描述】:

我有这样的功能:

public function checkItems(int $id, array $items)
{
    $this->validateItems($id, $items);

    foreach($items as $item) {
        ...// further code
    }

    return $items;
}

private function validateItems(int $id, array $items)
{
    foreach ($items as $item) {
        if (!is_int($item->itemId)) {
            continue;
        }
    }
}

问题是当我写这个时:

if (!is_int($item->itemId)) {
    continue;
}

在函数 checkItems() 内部(没有移动到另一个)它完美地工作,因为如果项目错误,..//更多代码不会被执行。如果信息无效,它基本上会返回 $items。

但是当我将验证移到另一个函数中时,尽管有 continue 语句,但最后它会再次循环并执行进一步的代码。

有人能告诉我如何通过验证转移到另一个函数来正确解决这个问题吗?

【问题讨论】:

    标签: php


    【解决方案1】:

    continue 仅在使用它的循环中有效 - foreach ($items as $item)

    如果你想在验证函数中使用它,你要么需要传回某种有效选项数组 - 要么在...// further code的for循环中使用验证

    类似:

    public function checkItems(int $id, array $items)
    {
        foreach($items as $item) {
            if ($this->validateItems($id, $item) {
                ...// further code
            }
        }
    
        return $items;
    }
    
    private function validateItems(int $id, array $item)
    {
        //$id is never used?
        if (!is_int($item->itemId)) {
            return false;
        }
        return true;
    }
    

    【讨论】:

      【解决方案2】:

      循环内的 continue 命令会跳过该循环内它下面的任何代码 并从顶部开始循环。

      因此将它放在任何循环的末尾都没有什么区别,因为没有更多的代码可以跳过。 并且循环从顶部开始,就好像没有继续命令一样。

      如果您以这种方式进行验证,则需要继续,然后继续 将始终引用它所在的循环。 因此,如果您将其移动到其他函数,它会跳过循环下方的代码执行 在该函数内部,但不会影响任何其他循环,尤其是在其他函数中。

      所以如果你在 checkItems() 中的 foreach 中使用 continue 它会在该函数的 foreach 中跳过命令。

      但如果您继续使用函数 validateItems() 并调用该函数 从 checkItems() 内部然后在 checkItems() 内部将不会使用 continue 在 validateItems() 里面

      到第二部分如何进行验证。

      你的验证器应该返回一个真/假 并在 checkItems() 内部进行测试 如果它是假的,那么你使用继续

      <?php
      
      public function checkItems(int $id, array $items)
      {
          $this->validateItems($id, $items);
      
          foreach($items as $item) {
      
              if(false === $this->validateItems($id, $items)) {
                  continue;
              }
      
              ...// further code
          }
      
          return $items;
      }
      
      private function validateItems(int $id, array $items)
      {
          foreach ($items as $item) {
              if (!is_int($item->itemId)) {
                  return false;
              }
          }
          return true;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-26
        • 2011-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        相关资源
        最近更新 更多