What are the best practices for setting up an autoloader in PHP to correctly load classes with namespaces?

When setting up an autoloader in PHP to correctly load classes with namespaces, it is important to follow best practices to ensure smooth class loading. One way to do this is by using the PSR-4 autoloading standard, which maps namespaces to directory structures. By following this standard, you can easily autoload classes without having to manually include them in your code.

// Autoloader using PSR-4 standard for class loading with namespaces
spl_autoload_register(function($className) {
    $prefix = 'Your\\Namespace\\Prefix\\';
    $baseDir = __DIR__ . '/src/';

    $len = strlen($prefix);
    if (strncmp($prefix, $className, $len) !== 0) {
        return;
    }

    $relativeClass = substr($className, $len);
    $file = $baseDir . str_replace('\\', '/', $relativeClass) . '.php';

    if (file_exists($file)) {
        require $file;
    }
});