# PHP Autoloading

Autoloading allows you to use classes without explicitly including the files that contain them using `include` or `require`. PHP automatically loads the class files when they are needed.

---

## 1. Why Autoload?
In large applications, you might have hundreds of classes. Including them all at the top of every script is tedious and inefficient. Autoloading solves this by loading only the files required for the current execution.

## 2. spl_autoload_register()
This is the standard way to register an autoloader function. When PHP encounters a class it doesn't know, it calls the registered autoloader functions one by one.

```php
spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

$obj = new MyClass1(); // Automatically includes MyClass1.php
$obj2 = new MyClass2(); // Automatically includes MyClass2.php
```

## 3. Handling Namespaces
If your classes use namespaces, your autoloader needs to handle the backslashes and directory separators.

```php
spl_autoload_register(function ($class) {
    // Convert namespace separators to directory separators
    $path = str_replace('\\', '/', $class) . '.php';
    
    if (file_exists($path)) {
        require $path;
    }
});

use App\Models\User;
$user = new User(); // Tries to load App/Models/User.php
```

## 4. Composer Autoloading (PSR-4)
In modern PHP development, you rarely write your own autoloader. Instead, you use **Composer**, which generates a highly optimized autoloader based on the PSR-4 standard.

```php
require __DIR__ . '/vendor/autoload.php';

// Now all classes installed via Composer are available
$log = new Monolog\Logger('name');
```

[[programming/php/php]] [[programming/php/php-composer]] [[programming/php/php-namespaces]]