prefix = rtrim( $prefix, '\\' ) . '\\'; $this->base_dir = rtrim( $base_dir, '/\\' ) . '/'; } /** * Registering a loader for the given prefix on the SPL autoload stack. * * @param string $prefix Namespace prefix, with or without a trailing separator. * @param string $base_dir Absolute path the prefix maps onto. * * @return self The registered loader. */ public static function register( string $prefix, string $base_dir ): self { $loader = new self( $prefix, $base_dir ); spl_autoload_register( array( $loader, 'load' ) ); return $loader; } /** * Loading the file backing a class name, when this loader owns its prefix. * * @param string $class_name Fully qualified class name handed over by PHP. */ public function load( string $class_name ): void { if ( 0 !== strpos( $class_name, $this->prefix ) ) { return; } $relative = substr( $class_name, strlen( $this->prefix ) ); // Defence in depth: keep the file path derived from a known-good string. if ( 1 !== preg_match( '/^[A-Za-z0-9_\\\\]+$/', $relative ) ) { return; } $path = $this->base_dir . str_replace( '\\', '/', $relative ) . '.php'; if ( is_readable( $path ) ) { require_once $path; } } }