duanjiu3486 2015-04-26 21:09
浏览 31

我创建了一个类,无法将值加载到其数组var中

The problem is that the addData function adds data to all variables but not to keywords array. As far as I can see, the keywords[1] is blank after the $keywords[]=$new_value; line. Why?? Here is my code:

class comment
{

    var $id;
    var $keywords;
    //some other vars

// This is the constructor function which assigns id property, creates keywords array.
function comment($newID) 
    {
        $this->id = $newID;
        $keywords = array();
    }

// This function is used to add data to one of the object's properties.
function addData ($prop, $new_value) 
{   // Convert the property name to lower case.
    $prop = strtolower($prop);
    if ($prop=='keywords'){
        $keywords[]=$new_value;
    }
    else 
    {
        $this->$prop = $new_value;
     }
}

}
  • 写回答

1条回答 默认 最新

  • duangan4406 2015-04-26 21:10
    关注

    You forgot the $this keyword which makes your $keywords variable just a local variable instead of a class member:

    $keywords[]=$new_value;
    

    should become

    $this->keywords[]=$new_value;
    

    You did the same thing in your comment() method.

    FYI, using var to declare class member variables has been obsolete for a long time. You should be using public, protected, and private as appropriate.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题