Skip to content

Instantly share code, notes, and snippets.

@JunaidQadirB
Created May 22, 2014 07:36
Show Gist options
  • Save JunaidQadirB/7533af3b9b5fd078910d to your computer and use it in GitHub Desktop.
Save JunaidQadirB/7533af3b9b5fd078910d to your computer and use it in GitHub Desktop.
Enable Class loading with Namespaces in CodeIgniter
/*
* Append this to the end of your application/config.php
* @see http://stackoverflow.com/questions/3700626/namespace-in-php-codeigniter-framework#21858556
*/
spl_autoload_extensions('.php'); // Only Autoload PHP Files
spl_autoload_register(function($classname) {
if (strpos($classname, '\\') !== false) {
// Namespaced Classes
$classfile = (str_replace('\\', '/', $classname));
if ($classname[0] !== '/') {
$classfile = APPPATH . 'libraries/' . $classfile . '.php';
}
require($classfile);
} else if (strpos($classname, 'interface') !== false) {
// Interfaces
strtolower($classname);
require('application/interfaces/' . $classname . '.php');
}
});
@wht123
Copy link

wht123 commented Apr 14, 2015

very good!

@vojtatranta
Copy link

Great!
You could event replace APPPATH with FCPATH and then it is framework-wide universal.

@NirmalLohar
Copy link

Can i also give namespace to controllers in CI 2.0.4

@Steveb-p
Copy link

I'd like to note that you can always register your namespaces and load them via composer. CodeIgniter in version 3.x specifically allows this via configuration.

@chiragvels
Copy link

Hi,
Is this effect all my .php which I do not wish to add as a namespace or only namespaced one file will affect?

@aaronwesel
Copy link

Worked for me. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment