PHP variable scope help
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->c开发者_如何学Goheck_for_profanity($row);
}
}
} else {
$pass_profanity = $validation->check_for_profanity($input);
return;
}
return;
}
check_for_profanity($array);
But I get the error:
Notice: Undefined variable: validation in /Library/WebServer/Documents/file.php on line 22
Fatal error: Call to a member function check_for_profanity() on a non-object in /Library/WebServer/Documents/file.php on line 2
I can't figure it out, any thoughts???
Thanks in advance!
You can either gain access to the variable in your function with global
:
function check_for_profanity($input){
global $validation;
...
}
Or, the better way would be to retrieve it via a parameter:
function check_for_profanity($input, $validation){
...
}
check_for_profanity($array, $validation);
Read the PHP manual - variable scope for more information
You're defineing $validation = new Validation; outside of the function. Therefore PHP doesn't know it exists.
Use the global
keyword: PHP.net: Variable Scope
$validation = new Validation;
function check_for_profanity($input){
global $validation;
//The rest of your function
}
精彩评论