Php 我创建了一个类,无法将值加载到其数组变量中
问题是addData函数会将数据添加到所有变量中,但不会添加到关键字数组中。据我所见,$keywords[]=$new_值之后的关键字[1]为空;线为什么?这是我的密码:Php 我创建了一个类,无法将值加载到其数组变量中,php,arrays,Php,Arrays,问题是addData函数会将数据添加到所有变量中,但不会添加到关键字数组中。据我所见,$keywords[]=$new_值之后的关键字[1]为空;线为什么?这是我的密码: class comment { var $id; var $keywords; //some other vars // This is the constructor function which assigns id property, creates keywords array. funct
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;
}
}
}
您忘记了$this关键字,这使得$keywords变量只是一个局部变量,而不是类成员:
$keywords[]=$new_value;
应该成为
$this->keywords[]=$new_value;
您在评论方法中也做了同样的事情
仅供参考,使用var声明类成员变量已经过时很长时间了。您应该适当地使用public、protected和private。我已经尝试了John Conde的建议,但得到了PHP语法检查:致命错误:无法使用[]在代码第117行读取$this->$keywords[]=$new\u value;谢谢你,我会把它们做成合适类型的vars。。。谢谢你在那一行之前可能有一个语法错误导致了这个错误我尝试了John Conde的建议,但是得到了PHP语法检查:致命错误:无法使用[]来读取第117行的代码$this->$keywords[]=$new_value;–狙击手j