One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class) … By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error.

It’s a feature that, if your environment supports it, should be used. But I digress.

The point of this post is how to combat the potential problem you may encounter when using a PHP autoloader in your code and alongside other plugins.

Your PHP Autoloader, Code, and Other Plugins

Specifically, if you have a plugin that’s using an autoloader and you’ve not written your code defensively enough, then there’s a chance you’ll see an error regarding Plugin_Autoloader.

Luckily, there are a few things that you can do to prevent this from happening though I’m making a few assumptions:

You have your main plugin file (or the bootstrap file) properly namespaced and that it has the use statement included correctly.

The calls to any other classes in the plugin are prefixed with their proper namespaces.

With that said and if you’re still seeing the above error message (or something like it), double-check that you have a standard top-level namespace for all of your classes.

Then, before doing any actual within the context of the function, make sure you have a conditional like this:

Simply put, this conditional verifies that the incoming class is part of the top-level namespace that you’re using throughout your project. If it doesn’t, then it will exit the function. Otherwise, it will continue execution with the rest of your code.

If you don’t include this, you risk your autoloader being called and trying to load classes from other plugins (that may not be following better practices).

Just Getting Started with WordPress?

I write a lot about WordPress development but if you're just getting started, I recommend checking out WPBeginner. They have free training videos, glossary, and more.

WPSessions hosts some of the best WordPress training you’ll find anywhere from many well-known speakers.

If there’s something you’d like to learn, and it’s not already covered here, it’s probably been covered at WPSessions. If you use the special link below you can watch your first session for free and get a steep discount on the full-access VIP membership.