Auto Loading Classes in Joomla

Joomla has its own way of including class files when needed. You can use the JLoader::register() function to register your class files.

When you need to create an instance of the class it will load the class file using the file information in the register.

You can register your class files like this


JLoader::register('MyClass', 'somepath/myclass.php');
JLoader::register('OtherClass', 'somepath/otherclass.php');

When you want to use the class, Joomla will automatically load the class using the file information in the register.


$obj = new MyClass();

The following will do class loading like the php __autoload() function. This will register all the class files in /classes directory. When you use a class it will be included from that directory.


$classpath = dirname(__FILE__).DS.'classes';
foreach( JFolder::files($classpath) as $file ) {
    JLoader::register(JFile::stripExt($file), $classpath.DS.$file);
}

Leave a comment

2 Comments.

  1. Hello Thanks for the information. I am trying to get a form working which has the option of running some php code after the submit.

    I include the class using require once but I just get hundreds of erros. I am assuming I need to do something like you have done. However I am not sure where I put the following code. Does it go in my php code or does it go in some joomla php file. Thanks.

    JLoader::register(‘MyClass’, ‘somepath/myclass.php’);
    2
    JLoader::register(‘OtherClass’, ‘somepath/otherclass.php’);