1

所以我开始使用MVC。我不使用框架。这只是自我练习。

所以这是我的注册部分:

    protected function _instance()
    {
        if ($_POST != null)
        {
            /**
            * Validating if forms are not empty
            **/

            if (self::validateForms())
            {
                echo 1;
            }
            else
            {
                new Error("One of the forums was empty..");
            }
        }
    }

    private static function validateForms()
    {
        $inputs = array (
            'username', 'password', 'repassword',
            'email', 'password_f', 'repassword_f',
            'display'
        );

        $i = 0;

        foreach ($inputs as $key)
        {
            if (isset($_POST[$key]) && !empty($_POST[$key]))
            {
                $i++;
                if ((int) $i == count($inputs))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }

现在它只需要检查是否设置了输入,如果没有,则抛出错误。但它似乎不起作用,因为它总是运行该错误。

$i每次输入满时都必须增长,但我认为不会。

当我做 echo$i时,它只回显“1”。

为什么它只循环一次?

4

2 回答 2

3

问题是您在第一次测试后返回循环中。

    foreach ($inputs as $key)
    {
        if (isset($_POST[$key]) && !empty($_POST[$key]))
        {
            $i++;
            if ((int) $i == count($inputs))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

应该

    foreach ($inputs as $key)
    {
        if (isset($_POST[$key]) && !empty($_POST[$key]))
        {
            $i++;
        } 
    }
    if ((int) $i == count($inputs))
    {
       return true;
    }
    else
    {
        return false;
    }

或更简洁地说

    foreach ($inputs as $key)
    {
        if (!isset($_POST[$key]) || empty($_POST[$key]))
        {
            return false;
        } 
    }
    return true;
于 2013-07-18T18:16:25.507 回答
0

您需要将检查$i排除在循环之外,以便在所有输入循环通过后检查实际设置了多少。否则,它在第一次检查,看到它不相等并返回 false。

foreach ($inputs as $key)
{
    if (isset($_POST[$key]) && !empty($_POST[$key]))
    {
        $i++;
    }
}
if ((int) $i == count($inputs))
{
    return true;
}
else
{
    return false;
}
于 2013-07-18T18:20:04.483 回答