在课堂上找不到Codeigniter方法

时间:2014-08-15 08:13:17

标签: php codeigniter

我刚开始学习CodeIgniter。我有一些PHP背景但不是OOP。所以我从他们的网站下载了CI并开始关注用户指南,但我遇到了一些像这样的问题

  

消息:未定义的属性:News_model :: $ load

     

文件名:models / news_model.php

     

行号:7

该行是__construct()函数

public function __construct()
{
    $this->load->database();
}

同样在下一个函数db field not found in class 'News model'method 'result_array' not found in class...

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

我知道这是非常基本的,但我现在有点迷失。如果有人可以解释或者至少指出我可以学习的其他好的教程,我会很高兴的。这是完整的class News_model

class News_model extends CI_Controller {

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

3 个答案:

答案 0 :(得分:3)

抱歉,但是:

class News_model extends CI_Controller {...}

???

答案 1 :(得分:3)

是的,user2883814是正确的,CodeIgniter中的每个模型都必须只扩展CI_Model类。 所以看起来应该是这样的:

class News_model extends CI_Model

然后您应该将模型加载到控制器以便使用。

顺便说一下,CodeIgniter中没有经常使用模型,而只能使用控制器和视图。

答案 2 :(得分:2)

模型扩展CI_Model类。

class News_model extends CI_Model { /* ... */ }

但是,使用控制器时,您需要在覆盖__construct方法时调用CI_Controller类的__construct方法:

class News extends CI_Controller {

    public function __construct()
    {
        // Call CI_Controller construct method first.
        parent::__construct();

        $this->load->database();
    }
}

由于您在继承者类中重写了__construct()方法,因此您应该首先调用父构造函数。

否则,当控制器正在初始化时,您将失去Loader and Core课程,而$this->load将无法正常工作。

相关问题