为什么以后继续;执行进一步的功能代码是否执行?

时间:2019-05-26 20:56:25

标签: php

我有类似的功能:

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语句,最后还是再次循环并执行了进一步的代码。

有人可以告诉我如何通过将验证移至另一个函数来正确解决此问题吗?

2 个答案:

答案 0 :(得分:1)

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

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

类似:

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

答案 1 :(得分:1)

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

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

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

因此,如果您在checkItems()中的foreach中使用Continue 它将在该函数的foreach中跳过命令。

但是如果继续移动,请继续使用validateItems()函数并调用该函数 从checkItems()内部开始,然后在checkItems()内部将不会继续使用 在validateItems()内部

第二部分如何进行验证。

您的验证器应返回true / false 并在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;
}
相关问题