在我创建的这个表单中,它会检查字段是否已设置且为空。我用两种方法创建了一个类,areSet()
为isset()
,areEmpty()
为empty()
。在areEmpty()
方法中,它应该显示" Empty"如果所有字段都为空,但即使填写了所有字段,它仍会显示"清空"。是因为我使用了implode()
函数吗?我需要别人的帮助才能指出我的代码出错了。
HTML
<form action="validate.php" method="post">
<input type="text" name="firstname" placeholder="First Name" autocomplete="off"><br>
<input type="text" name="lastname" placeholder="Last Name" autocomplete="off"><br>
<input type="text" name="email" placeholder="Email" autocomplete="off"><br>
<input type="text" name="username" placeholder="Username" autocomplete="off"><br>
<input type="password" name="password" placeholder="Password" autocomplete="off"><br>
<input type="password" name="passwordAgain" placeholder="Confirm password" autocomplete="off"><br>
<input type="submit" value="Submit">
</form>
validate.php
<?php
require 'include/class.php';
if(Input::areSet('firstname','lastname','email','username','password','passwordAgain')) {
if(Input::areEmpty('firstname','lastname','email','username','password','passwordAgain')) {
echo 'Empty';
} else {
echo 'Not empty';
}
}
class.php
<?php
class Input {
// isset()
public static function areSet(...$fields) {
$setFieldsArray = [];
foreach($fields as $field) {
$setFieldsArray[] = $_POST[$field];
}
return isset($setFieldsArray);
}
// empty()
public static function areEmpty(...$fields) {
$emptyFieldsArray = [];
foreach($fields as $field) {
$emptyFieldsArray[] = empty($_POST[$field]);
}
return implode(' || ', $emptyFieldsArray);
}
}
答案 0 :(得分:1)
我不知道你在做什么,通过设置一个数组,然后返回一个内爆阵列;但只需遍历$fields
,检查关联的$_POST
变量是否为空,如果是,则返回true
,如果没有,则返回false
:
public static function areEmpty(...$fields) {
foreach($fields as $field) {
if(empty($_POST[$field])) {
return true; // something was empty
}
}
return false; // none were empty
}
你也会遇到areSet()
的问题,因为你循环$fields
并设置一个数组元素$setFieldsArray
然后返回它是否为空,它永远不会为空因为你在其中创建了数组元素。