About Spl_autoload_register () and __autoload (), I believe most will choose the former? See the use of both:
Copy Code code 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 benefits of using Spl_autoload_register () are ineffable:
(1) Automatic loading of objects is more convenient, many frameworks do this:
Copy Code code 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 should know that the __autoload () function can only exist once, spl_autoload_register () Of course can register multiple functions
Copy Code code as follows:
function A () {
Include ' a.php ';
}
Function B () {
Include ' b.php ';
}
Spl_autoload_register (' a ');
Spl_autoload_register (' B ');
(3) SPL functions are rich, providing more functionality, such as Spl_autoload_unregister () logout of registered functions, spl_autoload_functions () to return all registered functions, and so on.
See the PHP Reference manual: A list of SPL functions.
Attention:
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 the Zend engine with spl_autoload () or Spl_autoload_call ()
Copy Code code as follows:
/**
The *__autoload method fails 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 in the following ways
*/
Spl_autoload_register (' __autoload ');