PHP变量范围帮助

时间:2011-07-14 10:22:29

标签: php scope

require_once('classes/class.validation.php');

$array = $_POST['array'];
$pass_profanity = false;
$validation = new Validation;
function check_for_profanity($input){
    if(is_array($input)){
        foreach($input as $row){
            if(is_array($row)){
                check_for_profanity($input);
            } else {
                $pass_profanity = $validation->check_for_profanity($row);
            }
        }
    } else {
        $pass_profanity = $validation->check_for_profanity($input);
        return;
    }
    return;
}
check_for_profanity($array);

但我收到错误:

  

注意:未定义的变量:验证   /Library/WebServer/Documents/file.php第22行

     

致命错误:在a上调用成员函数check_for_profanity()   /Library/WebServer/Documents/file.php中的非对象   在第2行

我无法弄清楚,有什么想法???

提前致谢!

3 个答案:

答案 0 :(得分:2)

您可以使用global

访问函数中的变量
function check_for_profanity($input){
    global $validation;
    ...
}

或者,更好的方法是通过参数检索它:

function check_for_profanity($input, $validation){
    ...
}

check_for_profanity($array, $validation);

阅读 PHP manual - variable scope 了解更多信息

答案 1 :(得分:1)

您正在定义$ validation = new验证;功能之外。因此PHP不知道它存在。

答案 2 :(得分:1)

使用global关键字:PHP.net: Variable Scope

$validation = new Validation;
function check_for_profanity($input){

    global $validation;

    //The rest of your function
}