In Codeigniter extends one controller into another controller

Viewed 2811

I am using codeigniter(3.1.5) and Ihave two controllers in my application/controllers/ folder. with name controller A and Controller B. I want to extends Controller A in Controller B so that I can use methods of Controller A. But it generates class not found error.

Here is my sample code:

A_Controller.php:

defined('BASEPATH') OR exit('No direct script access allowed');
class A_Controller extends CI_Controller {
  public function index()
  {
  }

  public function display(){
     echo 'base controller function called.';
  }
 }

B_Controller.php:

 defined('BASEPATH') OR exit('No direct script access allowed');
 class B_Controller extends A_Controller {

 }

I want to execute display() method of controller A in controller B. If i put controller A in application/core/ folder and in application/config/config.php file make

$config['subclass_prefix'] = 'A_';

then I can able to access methods of controller A.

Please suggest. Thanks in advance.

5 Answers

I found the solution using including parent controller on child controller like this -

require_once(APPPATH."modules/frontend/controllers/Frontend.php");

then my function like this -


class Home extends Frontend {

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

    function index() {
        echo $this->test(); //from Frontend controller
    }

}

I hope this will help.

add this script in B_Controller :

include_once (dirname(__FILE__) . "/A_Controller.php");

for example B_Controller.php :

defined('BASEPATH') OR exit('No direct script access allowed');
include_once (dirname(__FILE__) . "/A_Controller.php");
class B_Controller extends A_Controller {

 }
Related