2015-11-09 133 views
0

与PHP我想检查输入字段是否有效,而这样做,我把我的代码到不同的PHP文件,并将它们包含在主要的PHP文件(registerFunction.php) ,我这样做的原因是为了保持事件的组织性,只需点击一个按钮即可运行,但我得到的错误是我在registerFunction.php中声明的变量未在regValidation.php文件中声明。以下是错误消息我得到:未定义的变量:regErrors在PHP包含未声明的变量

我对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罚款$ regErr或可变但 registryValidation.php告诉我,$ regError未声明。

这是为什么?

+0

因为'regDecision'是一个函数,所以你需要'global $ regErrors'?另外请注意,您的电子邮件验证正在推向一个未定义的变量('regError'而不是'regErrors')。 – CompuChip

+0

谢谢!现在你告诉我这些,它已经清楚了,我已经解决了我的问题=) – Licentia

回答

1

默认情况下,当您在函数中使用变量时,它仅限于该函数的作用域。如果你有你想要的功能,使可用的全局(免费)变量,你必须使它global

<?php 

function regDecision() { 
    // Use the globally defined version of the variable, use: 
    global $regErrors; 

    return sizeof($regErrors) == 0; 
} 

?> 

注意如何我也换成你啰嗦了短return conditionif(condition) return true; else return false;

另外,我看到你在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