Sobes.tech
Junior — Middle

What is the purpose of the __autoload() function and what parameters does it accept?.

sobes.tech AI

Answer from AI

The __autoload() function in PHP is designed for automatic loading of classes when they are first used, if the class has not been declared yet.

It takes one parameter — the name of the class to load.

When the code encounters the use of a non-existent class, PHP calls __autoload($className), where $className is the name of that class. Inside the function, usually, a file with the class definition is included.

Example:

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

$obj = new MyClass(); // if MyClass is not loaded, __autoload will be called with 'MyClass'

Important: starting from PHP 5.3, it is recommended to use spl_autoload_register() instead of __autoload() for registering autoloaders.

What is the purpose of the __autoload() function and… - sobes.tech