Jonathan Jonathan - 10 months ago 41
PHP Question

Add public variable to all CI_Controller's and anything that extends them?

Hi I'd like to add a public variable ($this->data[]) to all instances of CI_Controllers, that way I can store some base rules for outputting a page (css/js, etc) then have each controller append to this array to add its own requirements (more css/js). I have a core library with custom view functions that take those arrays and inject them into the head tag of the page template.

The options I've thought of;

  1. Edit CI_Controller and add it there... guessing that's a bad idea.

  2. Create a shell controller that extends CI_Controller, add the var to that, then have every other controller extend the shell controller.

  3. Any other clever ways?

I've only been using CI for about a month and I've tried reading through the docs but I can't find any built in ways to do something like this? Has anyone encountered this before and if so how did you solve it?


[edit] Using PHP 5.3.x [/edit]

Answer Source

You can extend CI_Controller to have the functionality you want.


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

class MY_Controller extends CI_Controller {

    public function __construct()

    public function my_function()
        return "Cool return from my_function";



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

class Welcome extends MY_Controller {

    public function index()
        echo $this->my_function();//echo's "Cool return from my_function"

You simply define the functionality you want in MY_Controller. Then in your controllers, use extends MY_Controller instead of extends CI_Controller and you can call the functions anywhere inside those controllers.