Reputation: 2924
I have run into a problem. My php class structure is as follows:
class CustomerDao{
...
var $lastid;
function insertUser($user)
{
...
$lastid = mysql_insert_id();
return 0;
}
function getCustId()
{
return $lastid;
}
}
When i use this class, it let me access $lastid varibale in first function "insertUser", but it throws an error when i use $lastid in second function. I have no idea how to resolve this problem. Please guide.
Upvotes: 0
Views: 1817
Reputation: 15230
What you want to do is this:
function insertUser($user) {
...
$this->lastid = mysql_insert_id();
return 0;
}
function getCustId() {
return $this->lastid;
}
Note the this-keyword. Your first function works, because you assign a new (local!) variable $lastid
within your insertUser()
function - but it has nothing to do with the class property $lastid
.
Upvotes: 2
Reputation: 21563
Your code sample should look this:
class CustomerDao{
...
var $lastid;
function insertUser($user)
{
...
$this->lastid = mysql_insert_id();
return 0;
}
function getCustId()
{
return $this->lastid;
}
}
You need to reference the class ($this
) to access its $lastid
property. So it should be $this->lastid
;
Upvotes: 3
Reputation: 8858
to use a class variable inside the class use the $this
keyword
so to use $lastid
variable inside class use $this->lastid
Upvotes: 2
Reputation: 15580
In your first function you are creating a new variable called $lastid
which exists only within the scope of the function. In the second function this fails because there is no $lastid
variable declared within this function.
To access a class member you use the notation $this->lastid
.
class CustomerDao {
...
var $lastid;
function insertUser($user)
{
...
$this->lastid = mysql_insert_id();
return 0;
}
function getCustId()
{
return $this->lastid;
}
}
Upvotes: 4
Reputation: 449783
If you want to change an object property, you want the this
keyword:
$this->lastid = mysql_insert_id();
Reference: PHP Manual: Classes and objects
Upvotes: 5
Reputation: 18692
You're trying to access a class variable, which is done like this instead:
function getCustId() {
return $this->lastid;
}
Upvotes: 7