Sobes.tech
Junior

What is automatic class loading in PHP?

sobes.tech AI

Answer from AI

A mechanism that allows dynamically loading class files (interfaces, traits) when they are first used in a script, instead of explicitly including them with require or include.

Advantages:

  • Simplifies code structure.
  • Speeds up application execution (unnecessary classes are not loaded).
  • Eases dependency management.

Implemented using the spl_autoload_register() function, which registers autoload functions in a stack. When attempting to instantiate an undefined class, PHP calls the registered functions in order, passing the class name as an argument.

Example of a simple autoload function:

<?php
// This function will be called when attempting to use an undefined class
spl_autoload_register(function (string $className) {
    // Assume classes are stored in files with the .php extension
    // and the filename matches the class name (case-sensitive!)
    $filePath = $className . '.php';

    // Check if the file exists and include it
    if (file_exists($filePath)) {
        require_once $filePath;
    }
});

// Example of using a class that will be loaded automatically
$myObject = new MyClass();

The most common standard for autoloading is PSR-4. It defines how to map class namespaces to file paths in the filesystem.