Pregunta

When is __construct called and when is index called? And are there any other differences?

And what to put in __construct? Whats the best practice, should I put $this->load calls... ? what else?

class Site extends CI_Controller {

      public function __construct() {

          parent::__construct();
          echo 'Hello World2';

     }

     public function index() {

          echo 'Hello World1';

     }
}
¿Fue útil?

Solución

__construct() is called first, then according to URL is called index() or other functions.

public function __construct() should contain:

  1. allocating resources used in entire class ex. $this->load
  2. check user authentication (if entire class requires it)

public function index() should contain:

  1. allocating resources used only in this function
  2. calling views or displaying anything

it is bad design if public function __construct() contain:

  1. Displaying anything
  2. Any code required only for one function.

Otros consejos

index() will be executed while you call the index function or by default as you can say index() is an default function...Strightly we can say that __construct() is the one which will be the first method while an controller is called through its function works as constructor

__construct is the constucter of the class, while index() is the default method.

Suppose that you are calling http://yoursite.com/ this is equivalent to http://yoursite.com/your_default_controller/index

It means, if there is nothing in the third segment of your URL, index() of that controller is called by default.

You can initialize things at constucter and load view and models.

You can pass data to view at the index()

Suppose that you are calling http://yoursite.com/ this is equivalent to http://yoursite.com/your_default_controller/index

index() will be executed while you call the index function or by default as you can say index() is an default function...Strightly we can say that __construct() is the one which will be the first method while an controller is called through its function works as constructor

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top