我从CodeIgniter用户指南中编写了一个小应用程序,但是当我运行它时,显示给定的消息
Fatal error: Call to a member function get_news() on a non-object in C:\xampp\htdocs\CodeIgniter_Practice\application\controllers\news.php on line 11
代码是
class News extends CI_Controller{
public function _construct()
{
parent::_construct();
$this->load->model('news_model');
}
public function index()
{
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
$this->load->view('templates/header',$data);
$this->load->view('news/index',$data);
$this->load->view('templates/footer');
}
}
第11行是:
$data['news'] = $this->news_model->get_news();
答案 0 :(得分:0)
您也可以通过获取model
来致电Instance
:
class News extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->CI = & get_instance();
$this->CI->load->model('news_model');
}
public function index()
{
$data['news'] = $this->CI->news_model->get_news();
$data['title'] = 'News archive';
$this->load->view('templates/header',$data);
$this->load->view('news/index',$data);
$this->load->view('templates/footer');
}
}
答案 1 :(得分:0)
通过查看您的代码,我可以看到您在定义构造时错过了一个' _ '(下划线)。 它必须如下:
public function __construct()
{
parent::__construct();
$this->load->model('news_model');
}