Autoloader not finding classes from my plugin

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 ) {
          return;
        }
    }
}

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?

Topic namespace autoloading oop Wordpress

Category Web


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.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.