Skip to content
Advertisement

Codeigniter variables from constructor are undefined

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?

Advertisement

Answer

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 🙂

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement