Can anyone tell me why is the constructor in controller code using parent::__construct ? I only know it is because this is to use the method in parent class which is within CI_Controller. If so, why is the constructor in model code not using parent::__construct?
class News extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('news_model');
}
class News_model extends CI_Model
{
public function __construct()
{
$this->load->database();
}
- The reason this line is necessary is because your local constructor will be overriding the one in the parent controller class so we need to manually call it.
- Constructors are useful if you need to set some default values, or run a default process when your class is instantiated. Constructors can't return a value, but they can do some default work.
And Possible Duplicate of PHP Codeigniter - parent::__construct
Example
public function __construct()
{
parent::__construct();
$this->load->helper('date');
$this->load->library('session');
$this->load->model('My_model');
$this->load->library('cart');
}
you need to include parent::__construct();
to include the extended class default constructor initialization of codeigniter if you don't include that you will override the parent class constructor. function __construct()
always run when the class is instantiate, so if you want to load some libraries or initialize some value its good to put it there.