0

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.

0

6 Answers 6

7

You're trying to access a class variable, which is done like this instead:

function getCustId() { 
    return $this->lastid; 
}
Sign up to request clarification or add additional context in comments.

2 Comments

When i used $this with return statment it gives me this error: Cannot access empty property!!!
Make sure you don't put a dollar sign in front of the property name when using $this. So NOT like this: $this->$lastid, but do it like this: $this->lastid
5

If you want to change an object property, you want the this keyword:

$this->lastid = mysql_insert_id();

Reference: PHP Manual: Classes and objects

Comments

4

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; 
    }
}

1 Comment

It worked!!! Actually i was making mistake of using $this like: $this->$lastid; I corrected like this: $this->lastid; Thank You so much.
3

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;

Comments

2

to use a class variable inside the class use the $this keyword

so to use $lastid variable inside class use $this->lastid

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.