dsxrq28228
dsxrq28228
2014-07-05 02:21

从函数返回数组时出现“未定义变量”错误

  • return
  • function
  • php
  • arrays
已采纳

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!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • douhengdao4499 douhengdao4499 7年前

    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.

    点赞 评论 复制链接分享
  • duanlinjian5819 duanlinjian5819 7年前
    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;
    
    点赞 评论 复制链接分享