why do we still need parent constructor when controller class extends a parent controller?

__construct() is the constructor method of a class. It runs if you declare a new object instance from it. However, if a class implemented its own __construct(), PHP would only run the constructor of itself, not of its parent. For example:

<?php

class A {
  public function __construct() {
    echo "run A's constructor\n";
  }
}

class B extends A {
  public function __construct() {
    echo "run B's constructor\n";
  }
}

// only B's constructor is invoked
// show "run B's constructor\n" only
$obj = new B();

?>

In this case, if you need to run class A's constructor when $obj is declared, you'll need to use parent::__construct():

<?php

class A {
  public function __construct() {
    echo "run A's constructor\n";
  }
}

class B extends A {
  public function __construct() {
    parent::__construct();
    echo "run B's constructor\n";
  }
}

// both constructors of A and B are invoked
// 1. show "run A's constructor\n"
// 2. show "run B's constructor\n"
$obj = new B();

?>

In CodeIgniter's case, that line runs the constructor in CI_Controller. That constructor method should have helped your controller codes in some way. And you'd just want it to do everythings for you.


To answer your question directly from the Code Iginiter documentation:

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.

http://ellislab.com/codeigniter/user-guide/general/controllers.html#constructors


Extension used for all classes. __construct() used for that class that you use.

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.