用PHP我试图检查输入字段是否有效,而这样做我将我的代码放入不同的php文件并将它们包含在主php文件(registerFunction.php)中,原因我这样做是为了保持按钮单击时运行的组织,但是我得到一个错误,我在registerFunction.php中声明的变量在regValidation.php文件中未声明。以下是我得到的错误消息:未定义的变量:
中的regErrors我的registerFunction.php代码是:
<?php
//Create Error array
$regErrors = array();
//Add Date Functions
include "includes/functions/dateFunction.php";
//Checks if Register Screen Inputs are valid or not and pushes the errors into an array.
include "includes/functions/checkRegFields.php";
//
include "includes/functions/registryValidation.php";
if(regDecision()){
//register
}
else{
foreach ($regErrors as $errrorMessage) {
?>
<script>
$("#errors").append('<div class="alert alert-danger" role="alert"><?php echo $errrorMessage; ?></div>');
</script>
<?php
}
}
echo postDate();
?>
checkRegFields.php:
<?php
if(isset($_POST['registerButton'])){
if(($_POST['regEmail'])){
$regEmail = $_POST['regEmail'];
}
else{
array_push($regError,"Please Fill in the Email field");
}
if(($_POST['regUsername'])){
$regUsername = $_POST['regUsername'];
}
else{
array_push($regErrors,"Please Fill in the Username field");
}
if ((['regPassword']) and ($_POST['regPassword2'])) {
if( ($_POST['regPassword']) == ($_POST['regPassword2']) ){
$regPassword = $_POST['regPassword'];
}
else{
array_push($regErrors,"Passwords does not match!");
}
}
else{
array_push($regErrors,"Please Fill in the Password fields");
}
}
?>
最后我有registryValidation.php(我遇到错误):
<?php
function regDecision(){
if(sizeof($regErrors)==0){
return true;
}
else{
return false;
}
}
?>
checkRegFields.php可以使用$ regError变量,但是 registryValidation.php告诉我$ regError未声明。
为什么会这样?
答案 0 :(得分:1)
默认情况下,在函数中使用变量时,它仅限于该函数。如果您想要在函数中使用全局(免费)变量,则必须将其设为global
:
<?php
function regDecision() {
// Use the globally defined version of the variable, use:
global $regErrors;
return sizeof($regErrors) == 0;
}
?>
请注意我如何用较短的if(condition) return true; else return false;
替换你的啰嗦return condition
。
此外,我发现您在if
- 语句中拼错了变量名称,以验证您的电子邮件:
array_push($regError,"Please Fill in the Email field");
应该是
array_push($regErrors,"Please Fill in the Email field");
您可以通过启用严格报告来避免此类错误,这将通过添加
来警告您使用未定义的变量error_reporting(E_ALL | E_STRICT);
到脚本,或全局在php.ini中:
error_reporting = E_ALL | E_STRICT