CodeIgniter 3非对象上下文使用$this报错,如何在database.php中访问模型?
解决「在非对象上下文使用$this」的错误
问题根源是你注释掉了获取CI全局实例的代码,database.php作为配置文件,不属于类成员方法的上下文环境,无法直接使用$this,必须通过get_instance()获取CI的全局实例才能调用模型、会话等服务。
修正后的代码如下:
// 获取CI全局实例 $ci =& get_instance(); // 获取当前用户ID $user_id = $ci->auth->user_id(); // 加载用户模型并查询当前用户信息 $ci->load->model('users/user_model'); $current_user = $ci->user_model->find($user_id); echo $current_user->organisation; // 加载组织模型并查询对应组织信息 $ci->load->model('organisation/organisation_model'); $org = $ci->organisation_model->find($current_user->organisation);
额外提醒:
- 确保在调用
get_instance()时,CI的初始化流程已完成,避免因过早调用导致实例未生成的问题 - 尽量不要在配置文件中写入过多业务逻辑,建议将这类操作迁移到控制器或自定义库中,保持配置文件的简洁性
内容的提问来源于stack exchange,提问作者saghir SAGHIR
相关产品推荐
相关产品推荐

