The difference between spl_autoload_register() and __autoload(), splautoloadregister
This article mainly introduces the difference between spl_autoload_register() and __autoload(). Friends in need can refer to it.
Regarding spl_autoload_register() and __autoload(), I believe most people will choose the former? Look at the usage of both:
Copy codeThe 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 benefits of using spl_autoload_register() are indescribable:
(1) Automatically loading objects is more convenient, and many frameworks do this:
Copy codeThe 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 need to know that the __autoload() function can only exist once. Of course, spl_autoload_register() can register multiple functions
Copy codeThe code is 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 and provide more functions, such as spl_autoload_unregister() to unregister registered functions, spl_autoload_functions() to return all registered functions, etc.
See the PHP Reference Manual: About the SPL function list.
Note:
If the __autoload function has been implemented in your program, it must be explicitly registered to the __autoload stack middle. Because the
spl_autoload_register() function will replace the __autoload function in Zend Engine with spl_autoload() or spl_autoload_call()
Copy codeThe code is as follows:
/**
*__autoload method will be invalid after spl_autoload_register, because the autoload_func function pointer already points to the spl_autoload method
* You can add the _autoload method to the autoload_functions list by the following method
*/
spl_autoload_register( '__autoload' );
http://www.bkjia.com/PHPjc/1099423.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1099423.htmlTechArticleThe difference between spl_autoload_register() and __autoload(), splautoloadregister This article mainly introduces spl_autoload_register() and __autoload( ) difference, friends in need can refer to the information about spl_...