[英]Undefined variable Error when try to access PHP class variable in function
我遇到了一個問題。 我的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;
}
在第一個函數中,您將創建一個名為$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()
函數中分配了一個新的(local!)變量$lastid
,但這與類屬性$lastid
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.