I am trying to work with autoloader in my plugin.

In the main file of my plugin I have

use My_Plugin\Includes;

require_once( plugin_dir_path( __FILE__ ) . 'includes/class-autoloader.php' );

$autoloader = new Includes\Autoloader();

And in my includes/class-autoloader.php file I have

namespace My_Plugin\Includes;

class Autoloader() {
    public __construct() {
        spl_autoload_register( [ $this, 'autoloader' ] );

    public autoloader( $class_name ) {
        error_log( print_r( $class_name, true ) );

        if ( strpos( $class_name, 'My_Plugin' ) === false ) {

But none of the classes that I have in my plugin will be shown in my error_log.txt. I see classes from WooCommerce which I have activated on my test site.

Why am I not seeing my classes in the plugin?

1 Answer 1


Given the first PHP code snippet you posted, I don't see that you're using the class yet, which explains why you're not seeing your classes in the autoload error log that you're debugging with.

Note that use will not trigger PHP's autoloader.

use My_Plugin\Includes;

You need to actually instantiate a class, check that it exists, or do something else that requires the class to actually be loaded into memory at runtime. Only then will the autoload queue receive a request to load one of your class files.

As it stands, the only class you're using is the Autoloader class itself, which doesn't need to be autoloaded, because you've included the class file explicitly.

  • Hmmm, so how to avoid this issue? Should I just call the spl_autoload_register() out of the class? Without any instantiation?
    – dingo_d
    Nov 5, 2017 at 8:57
  • The point of autoloading is to NOT load classes until they are actually used for the first time. The goal of autoload is to minimize used resources by loading classes when they are needed only. Nov 5, 2017 at 8:59
  • @MilanPetrovic I know the concept of autoloading, I just never used it before, so I'm not sure how should I do it. I found some tutorials, but so far nothing worked...
    – dingo_d
    Nov 5, 2017 at 9:05
  • @dingo_d What you have is fine already. Just complete the work that you need to do in the autoload handler that you've registered. That way your class files will be loaded whenever you do use them. All that's left then, is just to use one of your classes. So create a test class named My_Plugin\Test, and run something like class_exists('My_Plugin\\Test') to trigger the autoloader for that class.
    – jaswrks
    Nov 5, 2017 at 9:08
  • Note the second $autoload argument to class_exists: php.net/manual/en/function.class-exists.php
    – jaswrks
    Nov 5, 2017 at 9:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.