1

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();
}
tereško
  • 58,060
  • 25
  • 98
  • 150
Zoe
  • 99
  • 1
  • 3
  • 8
  • You need to call the constructor of the parent, because if you don't you can't use any of the properties like 'load'. – Mubashar Abbas Aug 06 '15 at 07:19
  • [FOR you information we can use ` parent::__construct` in model file too](http://www.codeigniter.com/user_guide/general/models.html?highlight=models) – Saty Aug 06 '15 at 07:22

2 Answers2

0
  • 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.

Read Codeigniter Constructors

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

}
Community
  • 1
  • 1
Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
0

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.

winnie damayo
  • 426
  • 9
  • 17