If you’re using namespaces when working on your WordPress plugins (or whatever project you have going on), then you’re likely also taking advantage of a PHP autoloader.

PHP Autoloader in WordPress

Though this post isn’t really meant to be a tutorial on how to use them (I have another one of those coming up later), here’s the gist of what an autoloader is (or does):

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.

Depending on your environment, it may look something like this:

wp-content/plugins/namespace-demo/inc/autoloader.php:25:string'Plugin_Autoloader'

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

  1. You have your main plugin file (or the bootstrap file) properly namespaced and that it has the use statement included correctly.
  2. 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).

Category:
Articles
Tags:

    Leave a Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.