3

I'm using CI's Auth Tank library to query records for certain users.

The variable $user_id = tank_auth->get_user_id(); grabs the user id from the session. I want to pull records where user_id = $user_id.

From what I understood, constructors can load variables each time a class is initiated. Sort of like global variables. So I figured I'll set my $user_id in a model constructor so I can use it for multiple functions within the model class.

class My_model extends Model {

    function My_model() 
    {
        parent::Model();
        $user_id = $this->tank_auth->get_user_id();     
    }

        function posts_read() //gets db records for the logged in user
    {       
        $this->db->where('user_id', $user_id);
        $query = $this->db->get('posts');
        return $query->result();
    }
}

Next, I'm loading the model, creating an array in my controller, and sending the data to my view where I have a foreach loop.

When testing I get

Message: Undefined variable: user_id

in my model. It works however if I define the $user_id variable in my posts_read function, but I don't want to define it in every function that needs it.

What am I doing wrong here?

2 Answers 2

11

Variable scope problem. You should create class-level variables so that it is available in other functions as well like this:

class My_model extends Model {
    private $user_id = null;

    function My_model() 
    {
        parent::Model();
        $this->user_id = $this->tank_auth->get_user_id();     
    }

    // gets db records for the logged in user
    function posts_read()   
    {       
        $this->db->where('user_id', $this->user_id);
        $query = $this->db->get('posts');
        return $query->result();
    }
}

Notice the addition of $user_id after class declaration which is later used with $this->user_id :)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! It seems to work without a class-level var as well. Is that alright?
function My_model is not a constructor. Check this stackoverflow.com/questions/13555822/…
6

Pull it into global scope

class My_model extends Model {

    $user_id = 0;

    function My_model() {
        parent::Model();
        $this->user_id = $this->tank_auth->get_user_id();     
    }

    function posts_read() //gets db records for the logged in user {       
        $this->db->where('user_id', $this->user_id);
        $query = $this->db->get('posts');
        return $query->result();
    }
}

1 Comment

@CyberJunkie The same as did Safraz with NULL. I initialised it with a real value since no user will have 0 as his id. Both NULL and 0 are fine IMO

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.