When developing object-oriented applications in PHP, it is often necessary to invoke a variety of class libraries, so that the class libraries are referenced by require or include when using them. Now the __autoload () function can give us a lot of convenience.
In PHP 5, you can define a __autoload () function that will be called automatically when trying to use a class that has not yet been defined, and by calling this function, the scripting engine has a last chance to load the required class before PHP fails, and a parameter that the __autoload () function receives. is the class name of the class you want to load, so when you do the project, when the organization defines the name of the class, you need to follow certain rules, preferably with the class name as the center, or a uniform prefix or suffix to form the file name, such as xxx_classname.php, classname_ Xxx.php and is classname.php and so on.
This example attempts to load the MyClass1 and MyClass2 classes from the myclass1.php and myclass2.php files, respectively
function __autoload ($classname)
{
Require_once $classname. '. php ';
}
When the MyClass1 class does not exist, the __autoload () function is called automatically, passing in the parameter "MyClass1"
$obj = new MyClass1 ();
When the MyClass2 class does not exist, the __autoload () function is called automatically, passing in the parameter "MyClass2"
$obj 2 = new MyClass2 ();
?>
We can use the following processing methods in our program:
if (function_exists (' Spl_autoload_register '))
{
Spl_autoload_register (Array (' core ', ' autoload '));
}
Else
{
function __autoload ($class)
{
Return Core::autoload ($class);
}
Note: __autoload () is specifically designed for the non-existence of the Class!!! Many frameworks use this function to implement automatic loading of class files!!!