Call to a member function get_news() on a non-object in C:\\xampp\\htdocs\\CodeIgniter_Practice\\application\\controllers\\news.php on line 11

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

I wrote a small application from CodeIgnitor user guide but when I run it, display the given message

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 

The code is

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

Line 11 is :

$data['news'] = $this->news_model->get_news(); 

回答1:

By looking at your code, i could see that you've missed one '_'(underscore) while defining your construct. It has to be as below:

public function __construct()     {   parent::__construct();      $this->load->model('news_model');  }   


回答2:

You can call your model by getting your Instance as well:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!