我遇到了一个问题。我的php类结构如下:
class CustomerDao{
...
var $lastid;
function insertUser($user)
{
...
$lastid = mysql_insert_id();
return 0;
}
function getCustId()
{
return $lastid;
}
}
当我使用这个类时,它让我在第一个函数" insertUser"中访问$ lastid varibale,但是当我在第二个函数中使用$ lastid时它会抛出一个错误。我不知道如何解决这个问题。请指导。
答案 0 :(得分:7)
您正在尝试访问类变量,而不是这样:
function getCustId() {
return $this->lastid;
}
答案 1 :(得分:5)
如果要更改对象属性,则需要the this
keyword:
$this->lastid = mysql_insert_id();
答案 2 :(得分:4)
在第一个函数中,您将创建一个名为$lastid
的新变量,该变量仅存在于函数的范围内。在第二个函数中,这会失败,因为在此函数中没有声明$lastid
变量。
要访问班级成员,请使用符号$this->lastid
。
class CustomerDao {
...
var $lastid;
function insertUser($user)
{
...
$this->lastid = mysql_insert_id();
return 0;
}
function getCustId()
{
return $this->lastid;
}
}
答案 3 :(得分:3)
您的代码示例应如下所示:
class CustomerDao{
...
var $lastid;
function insertUser($user)
{
...
$this->lastid = mysql_insert_id();
return 0;
}
function getCustId()
{
return $this->lastid;
}
}
您需要引用类($this
)才能访问其$lastid
属性。所以它应该是$this->lastid
;
答案 4 :(得分:2)
在类中使用类变量使用$this
关键字
所以在类使用$lastid
$this->lastid
变量
答案 5 :(得分:2)
你想要做的是:
function insertUser($user) {
...
$this->lastid = mysql_insert_id();
return 0;
}
function getCustId() {
return $this->lastid;
}
请注意this-keyword。您的第一个函数有效,因为您在$lastid
函数中分配了一个新的(本地!)变量insertUser()
- 但它与类属性$lastid
无关。