Object Oriented PHP, a Class Auto Loader

I write a lot of object oriented PHP code. The one thing I’ve always wanted is for PHP to be clever, and be able to load my classes as and when I require them, much like me including a namespace in C# or Java. I could write all my classes in one file for each namespace, but I prefer to have each class in it’s own file.

A while ago I came across this excellent class that helped me in this situation. It is a class autoloader. PHP provides a nice function called spl_autoload_register which allows us to register a function we can call when a class not yet in our file is used.

The code above shows a class implementation of this. I can just include this file, and instantiate this class in any script, and then all files required are loaded when needed. This will work as long as I keep to a consistent file structure (keeping all my classes in a “classes” folder for example, and if I’m using namespaces, creating a folder for each namespace inside the classes folder).

To use this, you will need to change the code in the loader function to require_once the file path to where you hold your classes. I will explain my code for this

  • <code>dirname(__FILE__)</code> This provides an absolute path to the script this is written in (not the file it is included in). The dirname() function just gets the directory of this path. Since PHP 5.3.0 you can use __DIR__ instead.
  • <code>/../classes/</code> This is just the path from the file to my classes folder. Replace this with your relative path.
  • <code>str_replace(‘\\’, ‘/’, $classname) . ‘.php'</code> This converts any namespaces into the file structure (replacing the backslash used  with a forward slash). The final bit appends the PHP extension. You should be able to leave this code unaltered.

The final thing I would like to mention is how I passed the method into the spl_autoload_register function. I used an array to pass both the class, and the method from the class to call into the function. For more information on this you can find this in my previous post on a Benchmarking class to help with debugging in PHP.

Please feel free to use and update this code if you so wish. If you do, please share any improvements you make so others can benefit as well!

Leave a Reply