首页 文章

构造函数中的Codeigniter变量未定义

提问于
浏览
3

我正在使用CI的Auth Tank库来查询某些用户的记录 .

变量 $user_id = tank_auth->get_user_id(); 从会话中获取用户ID . 我想拉记录 user_id = $user_id .

根据我的理解,构造函数可以在每次启动类时加载变量 . 有点像全局变量 . 所以我想我会在模型构造函数中设置 $user_id ,这样我就可以将它用于模型类中的多个函数 .

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

接下来,我正在加载模型,在我的控制器中创建一个数组,并将数据发送到我的视图,在那里我有一个foreach循环 .

当测试我得到

消息:未定义的变量:user_id

在我的模型中 . 但是,如果我在 posts_read 函数中定义了 $user_id 变量,但是我不想在需要它的每个函数中定义它 .

我在这做错了什么?

2 回答

  • 9

    将其拉入全球范围

    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

    可变范围问题 . 您应该创建类级变量,以便它在其他函数中可用,如下所示:

    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 :)一起使用

相关问题