0
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);

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!

1
  • Define $validation in your function, check_for_profanity. Commented Jul 14, 2011 at 10:26

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

@FraserK Which of the two approaches did you go with from Sascha's answer?
1

You're defineing $validation = new Validation; outside of the function. Therefore PHP doesn't know it exists.

Comments

1

Use the global keyword: PHP.net: Variable Scope

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

    global $validation;

    //The rest of your function
}

3 Comments

since this is a recursive function will it not be debilitating for the system memory if its being stated as global??
@FraserK Honestly, I don't know. As far as I am aware, the global keyword essentially references the $GLOBALS array. The recursive nature of the function shouldn't have an impact since each call to the global keyword will cause the application to constantly reference the same object. However, I don't know that as a fact.
okay :) i just realised that the level of recursion will not go that deep anyways :) so it should be fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.