我正在关注CodeIgniter的用户指南,我对此部分遇到了问题http://www.codeigniter.com/user_guide/tutorial/news_section.html
它在Call to a member function get_news() on a non-object
方法的第一行报告错误index
。看起来如果模型的加载不起作用。我已更改news_model
的所有News_model
,以检查是否是原因,但有任何更改。
两年前有同样的问题Call to a member function get_news() on a non-object in C:\xampp\htdocs\CodeIgniter_Practice\application\controllers\news.php on line 11但是那个案例的解决方案对我不起作用,因为我对构造的调用是正确定义的。
应用/控制器/ News.php
<?php
class News extends CI_Controller {
public function __contruct() {
parent::__construct();
$this->load->model('news_model');
$this->load->helper('url_helper');
}
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');
}
public function view($slug = NULL) {
$data['news_item'] = $this->news_model->get_news($slug);
if (empty($data['news_item'])){
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
}
应用程序/模型/ News_model.php
<?php
class News_model extends CI_Model {
public function __construct(){
$this->load->database();
}
public function get_news($slug = FALSE) {
if ($slug === FALSE) {
$query = $this->db->get('news');
return $query->result_array();
}
$query = $this->db->get_where('news', array('slug' => $slug));
return $query->row_array();
}
}
答案 0 :(得分:1)
我想知道这是否值得回答,但你有一个错字(__construct()
中缺少s,所以从未调用过)。此外,url_helper
仅称为url
,但您没有收到错误,因为它从未被调用过。
<?php
class News extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('news_model');
$this->load->helper('url');
}
答案 1 :(得分:1)
控制器中应该是__construct
...你错过了