Sobes.tech
Junior — Middle

Explain the purpose and principle of operation of the __autoload() function in PHP.

sobes.tech AI

Answer from AI

The __autoload() function in PHP is designed for automatic loading of classes when they are first used, if they haven't been included manually.

How it works: When the code attempts to create an object or use a class that hasn't been loaded yet, PHP calls the __autoload() function with the name of that class. Inside this function, the logic to include the file with the class definition is usually implemented, for example, using require or include.

Example:

function __autoload($className) {
    include_once 'classes/' . $className . '.php';
}

$obj = new MyClass(); // If MyClass is not loaded, __autoload() will be called automatically

Important: starting from PHP 5.3, it is recommended to use the spl_autoload_register() function, which allows registering multiple autoloaders and managing them more flexibly. __autoload() is considered deprecated.