SoFunction
Updated on 2025-03-09

Basic knowledge of php: classes and objects (2) Automatically load objects

Automatically load the object:
Many developers create a PHP source file for the definition of each class when writing object-oriented applications. A big annoyance is having to write a long list of included files at the beginning of each script (one file per class).
In PHP 5, this is no longer needed. You can define a __autoload function that will be automatically called when trying to use a class that has not been defined yet. By calling this function, the script engine has the last chance to load the required class before the PHP error fails.

This example tries to load the MyClass1 and MyClass2 classes from the   and    files respectively.
function __autoload($class_name) {
   require_once $class_name . '.php';
}
$obj  = new MyClass1();
$obj2 = new MyClass2();
Notice:
The exception thrown in the __autoload function cannot be caught by the catch statement block and leads to a fatal error.