The autoloader is similar to a troll riding a unicorn on a purple rainbow. You know it happens on a daily basis, but you’ve never seen it happen, even though you wish you had.

If you read my last post about “My PHP Story,” then you may know I’ve been using PHP since before the autoloader came to be a thing. We would always include all of the files we needed using a single file or on the fly when we needed them. When I first read about the PHP autoloader, I was a bit confused and wondered where that troll got his unicorn, but now I use it every day (like a boss).

## How It Helps

There may be more benefits to using the autoloader than the ones I mention, but here are some of my favorite ways it helps.

• One include file, instead of many
• Cleaner code since there are less includes
• Composer can generate it for you
• Only classes you are using get included

It simplifies the inclusion of a file based on the instantiation of a class. So, when you instantiate a class, it includes that file.

There are two ways that I know of to use an autoloader, and I’ll list both. The second way is my preferred way.

As with most things, you can always make your own. In most cases, you won’t want to do this, and you should use Composer. Below is a very basic example of making your own autoloader. This example is also using a closure, but I’ll talk more about those another time.


<?php
spl_autoload_register(function ($className) { include$className . '.php';
});


As you can see from the example above, it accepts a parameter called \$className, and it then uses that to include the file that corresponds to that class. That is all you need to do. You would then include this file at the top of your PHP scripts and instantiate your classes.

### Using Composer

Yay! Composer! If you reference the composer.json file below that I pulled from my PHP project boilerplate, then you’ll notice the autoload PSR-4. You can then run composer install or composer dump-autoload, and it will generate an autoloader for you.


{
"name": "wappr/library-name",
"description": "",
"version": "0.1.0",
"keywords": [""],
"psr-4": {
"wappr\": "src/"
}
},
"require": {
"php": ">=5.6"
}
}


Then you will include vendor/autoload.php at the top of your PHP files. This will allow you to instantiate your classes and have them included by the autoloader.

## Conclusion

I hope this helps you understand autoloading. You may not struggle with it like I did and I hope you don’t. If you do, feel free to email me, and I’ll help you out.