How to add autoload-function to CodeIgniter? How to add autoload-function to CodeIgniter? codeigniter codeigniter

How to add autoload-function to CodeIgniter?


You can add your auto loader above to app/config/config.php. I've used a similar autoload function before in this location and it's worked quite neatly.

function __autoload($class){    if (strpos($class, 'CI_') !== 0)    {        @include_once(APPPATH . 'core/' . $class . EXT);    }} 

Courtesy of Phil Sturgeon. This way may be more portable. core would probably be records for you; but check your paths are correct regardless. This method also prevents any interference with loading CI_ libs (accidentally)


the User guide about Auto-loading Resources is pretty cleat about it.

To autoload resources, open the application/config/autoload.php file and add the item you want loaded to the autoload array. You'll find instructions in that file corresponding to each type of item.


I would suggest using hooks in order to add this function to your code.

Enable hooks in your config/config.php

$config['enable_hooks'] = TRUE;


In your application/config/hooks.php add new hook on the "pre_system" call, which happens in core/CodeIgniter.php before the whole system runs.

$hook['pre_system'] = array(    0 => array(                 'function' => 'load_initial_functions',        'filename' => 'your_hooks.php',        'filepath' => 'hooks'    ));

Then in the hooks folder create 2 files:

First: application/hooks/your_functions.php and place your __autoload function and all other functions that you want available at this point.

Second: application/hooks/your_hooks.php and place this code:

function load_initial_functions(){    require_once(APPPATH.'hooks/your_functions.php');}

This will make all of your functions defined in your_functions.php available everywhere in your code.