dsxrq28228 2014-07-04 18:21
浏览 125
已采纳

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

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 2014-07-04 18:35
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部