簡體   English   中英

未定義的變量嘗試訪問函數中的PHP類變量時出錯

[英]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; 
}

如果要更改對象屬性,則需要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()函數中分配了一個新的(local!)變量$lastid ,但這與類屬性$lastid

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM