This article mainly introduces the differences between spl_autoload_register () and _ autoload (). For more information about spl_autoload_register () and _ autoload (), I believe most of them will select the former? See the usage of the two:
The code is as follows:
// _ Autoload usage
Function _ autoload ($ classname)
{
$ Filename = "./class/". $ classname. ". class. php ";
If (is_file ($ filename ))
{
Include $ filename;
}
}
// Spl_autoload_register usage
Spl_autoload_register ('load _ class ');
Function load_class ($ classname)
{
$ Filename = "./class/". $ classname. ". class. php ";
If (is_file ($ filename ))
{
Include $ filename;
}
}
The benefit of using spl_autoload_register () is immutable:
(1) it is more convenient to automatically load objects. many frameworks do this:
The code is as follows:
Class ClassAutoloader {
Public function _ construct (){
Spl_autoload_register (array ($ this, 'loader '));
}
Private function loader ($ className ){
Echo 'trying to load', $ className, 'via', _ METHOD __, "() \ n ";
Include $ className. '. php ';
}
}
$ Autoloader = new ClassAutoloader ();
$ Obj = new Class1 ();
$ Obj = new Class2 ();
(2) you must know that the _ autoload () function can only exist once. of course, spl_autoload_register () can register multiple functions.
The code is as follows:
Function (){
Include 'A. php ';
}
Function B (){
Include 'B. php ';
}
Spl_autoload_register ('A ');
Spl_autoload_register ('B ');
(3) SPL functions are rich and provide more functions, such as spl_autoload_unregister () to deregister registered functions, spl_autoload_functions () to return all registered functions.
For details, see The PHP Reference Manual: SPL function list.
Note:
If the _ autoload function has been implemented in your program, it must be explicitly registered to the _ autoload stack. Because
The spl_autoload_register () function replaces the _ autoload function in Zend Engine with spl_autoload () or spl_autoload_call ()
The code is as follows:
/**
* The _ autoload method will expire after spl_autoload_register, because the autoload_func function pointer has pointed to the spl_autoload method
* You can add the _ autoload method to the autoload_functions list using the following method:
*/
Spl_autoload_register ('_ autoload ');