Skip to content
PHP Logo

What is the role of an autoloader in handling namespaces in PHP?

When working with namespaces in PHP, it can become tedious to manually include each class file that corresponds to a specific namespace. This is where an autoloader comes in handy. An autoloader is a function that automatically includes the necessary class files based on the namespace and class name, simplifying the process of managing namespaces in PHP.

php
// Autoloader function to handle namespaces in PHP
spl_autoload_register(function ($class) {
    // Convert namespace separators to directory separators
    $classFile = str_replace('\\', '/', $class) . '.php';
    
    // Check if the file exists and include it
    if (file_exists($classFile)) {
        include $classFile;
    }
});