开发者

Codeigniter variables from constructor are undefined

开发者 https://www.devze.com 2023-02-03 20:13 出处:网络
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 pu开发者_如何学运维ll record

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 pu开发者_如何学运维ll 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?


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 :)


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();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消