user2503896
user2503896

Reputation:

Why construct function creates issue in codeigniter 3?

I am new to codeigniter 3.x, in codeigniter 3.x when i write

class Auth extends CI_Controller {

    public function __construct() {
        parent::__construct();
        echo "ya";
    }
}

it shows me error

404 Page Not Found

The page you requested was not found.

and when i write

class Auth extends CI_Controller {

    public function __construct() {
        parent::__construct();
        echo "ya";
    }
    public function index() {
        echo "aya";exit;
    }
}

it works fine and shows output as {yaaya}. can anyone let me know y is this?

Upvotes: 1

Views: 504

Answers (2)

Sougata Bose
Sougata Bose

Reputation: 31749

It is happening because CI was looking for that index() when you have not provided which action to go for. For the first case it is not present so it threw the error. But in the second case it was there so it worked. you cant call __construct() explicitly.

The default url pattern it look for controller/action. If the action is not provided the it will look for index() in that controller.

So when it get the index(), it instantiates the controller class and the __construct() get called.

Upvotes: 0

Saty
Saty

Reputation: 22532

The reason behind this is when you run the url

http://ip/cifolder/index.php/controller

By default it look into index() of this controller

If you use url like

http://ip/cifolder/index.php/controller/function

It will look into that function of your controller

and if you not written any function in you controller just __construct

function __construct() {
        parent::__construct();
    }

it means no index() function it will show you 400 error

Upvotes: 1

Related Questions