简体   繁体   中英

Codeigniter method not found in class

I just started to learn CodeIgniter. I have some background in PHP but not in OOP. So I've downloaded the CI from their website and started to follow the user guide but I faced some problems like this

Message: Undefined property: News_model::$load

Filename: models/news_model.php

Line Number: 7

On that line is the __construct() function

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

Also in the next function db field not found in class 'News model' and 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();
}

I know that this is very basic but I'm a bit lost right now . I'll be glad if someone can explain or at least point me to another good tutorial/s that I can learn. Here is the full 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();
}
}

sorry but:

class News_model extends CI_Controller {...}

???

Yes, user2883814 is right, every model in CodeIgniter must extend only CI_Model class. So it should look like this:

class News_model extends CI_Model

Then you should load your model to controller for using.

By the way models aren't used in CodeIgniter so often, and you can use only controllers and views instead.

Models should extend the CI_Model class.

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

However, using Controllers you need to call __construct method of CI_Controller class when you override the __construct method:

class News extends CI_Controller {

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

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

Since you're overriding the __construct() method within the inheritor class, you should call the parent constructor at first.

Otherwise, when the controller is initializing, you'll lose Loader and Core class and $this->load will never work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM