所以我开始使用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”。
为什么它只循环一次?
答案 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;
}