Error-404
Error-404

Reputation: 37

'Undefined variable' error when returning an array from a function

Essentially, I have a message class with a function that can write to an array. I want to then return that instance of an array through a function when called.

This is the class:

class Message
{
    public $formMessages = array();

    public function __construct()
    {
    }

    public function writeFormMessage($field, $message)
    {
        $formMessages[$field] = $message;
    }

    public function getFormMessages()
    {
        return $this->formMessages;
    }
}

Here is how I am attempting to grab the formMessages array from another file. Yes I already have an instance of the Message class in said file.

$test = $message->getFormMessages();

It fails this predicate, though it doesn't seem to be seeing the array anyhow:

if (!empty($test))
{ 
}

The php error was 'Undefined variable: formMessages in C:\xampp\htdocs\test\classes\message.class.php on line 45'

Edit: Thanks all!

Upvotes: 0

Views: 3803

Answers (2)

mario
mario

Reputation: 145482

Look at this line in your writeFormMessage method:

$formMessages[$field] = $message;

That attempts to access a local variable. (Which doesn't exist within that method.)

Compare to this usage in getFormMessages() however:

return $this->formMessages;

There you are correctly accessing the intended property.

Use the same $this-> syntax for both.

Upvotes: 3

hlscalon
hlscalon

Reputation: 7552

public function writeFormMessage($field, $message)
{
    $formMessages[$field] = $message;
}

public function getFormMessages()
{
    return $this->formMessages;
}

You are saying different things here, that's why you got empty from the result. You think you are refering to the same var, but you are not. $formMessages is a variable that exists only inside the WriteFormMessage function while $this->formMessages exists outside it.

Then you have to reference it with $this to get proper results.

    $this->formMessages[$field] = $message;

Upvotes: 1

Related Questions