Sobes.tech
Junior — Middle

What is the purpose of the __autoload() function in PHP?

sobes.tech AI

Answer from AI

The __autoload() function in PHP is intended for automatic loading of classes when they are first used, if they haven't been included yet. This allows avoiding manual include or require statements for each class.

When an object of a class that hasn't been loaded yet is created, PHP calls the __autoload() function with the class name. Inside __autoload(), the logic for including the file with the class definition is usually implemented.

Example of using __autoload():

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

$obj = new MyClass(); // This will automatically include MyClass.php

Note: since PHP 5.3, it is recommended to use spl_autoload_register() as __autoload() is considered deprecated.