Attila Naghi
Attila Naghi

Reputation: 2686

how do i extend a class in codeigniter?

this is my controller: common :

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Common extends CI_Controller {

    public function __construct() { 

        parent::__construct();

    }
    public function test(){
        echo 1;
    }

}

and this the second controller (register):

class Register extends Common {

    public function __construct() { 

        parent::__construct();

    }
    public function user_registration(){
        $this->test();
    }
}

when i access the user_registration function it shows me this error: Fatal error: Class 'Common' not found in /home/attilana/domains/attila-naghi.com/public_html/application/controllers/register.php on line 3

How do i access the test() function from the class common , in the user_registration function from the class register?

Upvotes: 0

Views: 160

Answers (1)

Burak Ozdemir
Burak Ozdemir

Reputation: 5332

In Codeigniter calling a controller from another controller even in an example like this is not possible because of the situation that it doesn't allow multiple controller instances in a request. Because of this situation you have three main options actually.

First, you can extend Codeigniter's base controller, CI_Controller, with MY_ prefix so that Codeigniter will recognize it as a common base class. The main idea here is to write the methods that will be common in most of your controllers.

If we take a look at your example and try to adapt it as mentioned above :

Initially, you need to extend the CI_Controller class:

class MY_Controller extends CI_Controller {

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

    public function test(){
        echo 1;
    }

}

Secondly, create your register controller as below:

class Register extends MY_Controller {

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

    public function user_registration(){
        $this->test();
    }
}

Another possibility is you can create a helper and call that function globally or you can create a library and load it within your controller and call that.

For further information, you can read from here: http://ellislab.com/codeigniter/user-guide/general/core_classes.html or from old docs: https://github.com/EllisLab/CodeIgniter/wiki/MY-Controller

Upvotes: 2

Related Questions