*/ private static array $prefixes = array(); /** * Register a namespace prefix. * * @param string $prefix Namespace prefix with a trailing backslash. * @param string $base_dir Base directory with a trailing slash. */ public static function register( string $prefix, string $base_dir ): void { if ( array() === self::$prefixes ) { spl_autoload_register( array( self::class, 'load' ) ); } self::$prefixes[ $prefix ] = rtrim( $base_dir, '/\\' ) . '/'; // Longest prefix first, so nested namespaces (e.g. WPInterface\ProductReviews\Dev\) win. uksort( self::$prefixes, static fn( string $a, string $b ): int => strlen( $b ) <=> strlen( $a ) ); } /** * Load a class file if it belongs to a registered prefix. * * @param string $class_name Fully qualified class name. */ public static function load( string $class_name ): void { foreach ( self::$prefixes as $prefix => $base_dir ) { if ( 0 !== strpos( $class_name, $prefix ) ) { continue; } $relative = substr( $class_name, strlen( $prefix ) ); $file = $base_dir . str_replace( '\\', '/', $relative ) . '.php'; if ( is_readable( $file ) ) { require_once $file; return; } } } }