Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试访问函数中的PHP类变量时出现未定义变量错误_Php - Fatal编程技术网

尝试访问函数中的PHP类变量时出现未定义变量错误

尝试访问函数中的PHP类变量时出现未定义变量错误,php,Php,我遇到了一个问题。我的php类结构如下: class CustomerDao{ ... var $lastid; function insertUser($user) { ... $lastid = mysql_insert_id(); return 0; } function getCustId() { return $lastid; } } 当我使用这个类时,它允许我在第一个函数insertUser中访问

我遇到了一个问题。我的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


要在类内使用类变量,请使用$this关键字


因此,要在类内使用$lastid变量,请使用$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

您要做的是:

function insertUser($user) {
  ...
  $this->lastid = mysql_insert_id();
  return 0;
}

function getCustId() { 
  return $this->lastid; 
}

注意这个关键字的用法。您的第一个函数可以工作,因为您分配了一个新的本地!insertUser函数中的变量$lastid-但它与类属性$lastid无关。

当我将$this与return station一起使用时,它给了我以下错误:无法访问空属性!!!当使用$this时,请确保不要在属性名称前放置美元符号。所以不要这样:$this->$lastid,但要这样做:$this->lastid有效!!!实际上,我在使用$this时犯了一个错误,比如:$this->$lastid;我更正如下:$this->lastid;非常感谢你。
class CustomerDao{
...
var $lastid;

  function insertUser($user)
  {
    ...
    $this->lastid = mysql_insert_id();
    return 0;
  }
      function getCustId()
  { 
    return $this->lastid; 
  }
    }
function insertUser($user) {
  ...
  $this->lastid = mysql_insert_id();
  return 0;
}

function getCustId() { 
  return $this->lastid; 
}