Create your own PHP Autoloader

Create your own PHP Autoloader

   Leave a comment   
http://bit.ly/1wTPGIM
Loading...

If you’ve worked with any large file in PHP you will probably have come across a large block of include statements at the top of it. Includes allow one file to include many other files and are used a lot in OOP. A large amount of includes at the top your code poses two major annoyances: firstly they’re taking up valuable space which could otherwise be used for more important things; secondly because of their explicit nature, they get left in the code over time when they’re not needed or the file they are directing to gets move resulting in warnings and errors.

Since PHP 5.1, there has been a way to combat this problem of includes with a very neat little function called spl_autoload_register (info). This function allows you to set up an action when a class is called in the code, but is missing (due to no include). Within this action, you can then include the class dynamically becuase the class name is passed into the function. Here is one example:

spl_autoload_register(
    function ($class) {
        $file = 'classes/' . $class . '.php';
        if (file_exists($file) && !class_exists($class, false)) {
            include $file;
        }
    }
);

This function does rely on the project having a strict naming convention and folder structure because of how they’re called. It also needs a little tweaking with namespaces as the namespace will be passed into the function along with the class name.

Do you have experience with autoloading? Let us know in the comments

Photo by 12th St David



Leave a Reply

Your email address will not be published. Required fields are marked *