What is the function of __construct() in CodeIgniter?

mohsen picture mohsen · Jun 3, 2016 · Viewed 33k times · Source

I work with CodeIgniter framework and I'm new to this. In the following code, __construct() function is used for loading a model.

  • Why do I need to use __construct()?
  • When should I use this function?
  • What is parent::__construct()?

Code

function __construct() {
    parent::__construct();
    $this->load->model('example');
}

Answer

Davy Baccaert picture Davy Baccaert · Jun 4, 2016

The construct function lets you use things over the entire class. This way you don't have to load the model/language/settings in every method.

Say you have a model and language that you want to load for that class, you can do this in the constructor. If you have for example an email method in the class and only use email in that class, you dont have to set this in the constructor but in the method. This way it doesn't get loaded unneeded for all the other methods that dont use it.

    class Contact extends CI_Controller {

      public function __construct(){
        parent::__construct();
        $this->load->model('contact_model', 'contact');
      }

      public function index(){
        $data['contact'] = $this->contact->getContact();
        $this->load->view('contact', $data);
      }

      public function send_mail(){
        /* Mail configuration - ONLY USED HERE */
        $config = array('protocol' => 'mail',
                    'wordwrap' => FALSE,
                    'mailtype' => 'html',
                    'charset'   => 'utf-8',
                    'crlf'      => "\r\n",
                    'newline'   => "\r\n",
                    'send_multipart' => FALSE
                    );
        $this->load->library('email', $config);
        $records = $this->contact->getCompany();

        $this->email->from( $setmail, $records['CompanyName'] );
        $this->email->to( $to );
        $this->email->subject( $subject );
        $this->email->message( $html );
        $this->email->send();
      }

    }

From php: http://php.net/manual/en/language.oop5.decon.php

PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.