PHP检查是否所有输入都设置不起作用?

时间:2013-07-18 18:07:56

标签: php scope

所以我开始使用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必须增长,但我认为不会。

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

为什么它只循环一次?

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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;
}