Codeigniter variables from undefined constructor

I use the CI Auth Tank library to request records for specific users.

The variable $user_id = tank_auth->get_user_id();captures the user ID from the session. I want to print notes where user_id = $user_id.

From what I understand, constructors can load variables every time a class is initiated. Like global variables. Therefore, I decided that I would install my own $user_idin the model constructor so that I could use it for several functions in 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();
    }
}

Then I load the model, create an array in my controller and send the data to my view, where I have a foreach loop.

When testing, I get

Message: Undefined variable: user_id

. , $user_id posts_read, , .

?

+3
2

. , :

class My_model extends Model {
    private $user_id = null;

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

$user_id , $this->user_id:)

+8

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

Source: https://habr.com/ru/post/1784401/


All Articles