我遇到了一个问题。我的php类结构如下:
class CustomerDao{
...
var $lastid;
function insertUser($user)
{
...
$lastid = mysql_insert_id();
return 0;
}
function getCustId()
{
return $lastid;
}
}
当我使用这个类时,它允许我在第一个函数"insertUser"中访问$lastid varibale,但当我在第二个函数中使用$lastid时,它会抛出一个错误。我不知道如何解决这个问题。请引导。
您正在尝试访问一个类变量,操作如下:
function getCustId() {
return $this->lastid;
}
如果要更改对象属性,则需要this
关键字:
$this->lastid = mysql_insert_id();
参考:PHP手册:类和对象
在第一个函数中,您将创建一个名为$lastid
的新变量,该变量仅存在于函数的范围内。在第二个函数中,由于该函数中没有声明$lastid
变量,因此此操作失败。
要访问类成员,请使用符号$this->lastid
。
class CustomerDao {
...
var $lastid;
function insertUser($user)
{
...
$this->lastid = mysql_insert_id();
return 0;
}
function getCustId()
{
return $this->lastid;
}
}
您的代码示例应该是这样的:
class CustomerDao{
...
var $lastid;
function insertUser($user)
{
...
$this->lastid = mysql_insert_id();
return 0;
}
function getCustId()
{
return $this->lastid;
}
}
您需要引用类($this
)来访问其$lastid
属性。所以它应该是$this->lastid
;
要在类中使用类变量,请使用$this
关键字
所以要在类内使用$lastid
变量,请使用$this->lastid
您想要做的是:
function insertUser($user) {
...
$this->lastid = mysql_insert_id();
return 0;
}
function getCustId() {
return $this->lastid;
}
注意这个关键字。第一个函数有效,因为您在insertUser()
函数中分配了一个新的(局部!)变量$lastid
,但它与类属性$lastid
无关。