Home  >  Article  >  php教程  >  spl_autoload_register()和__autoload(),splregisterautoload

spl_autoload_register()和__autoload(),splregisterautoload

WBOY
WBOYOriginal
2016-06-13 08:41:49944browse

spl_autoload_register()和__autoload(),splregisterautoload

关于spl_autoload_register()和__autoload()

看两者的用法:

 

//__autoload用法 function __autoload($classname) {     $filename = "./class/".$classname.".class.php";     if (is_file($filename))     {         include $filename;     } }
//spl_autoload_register用法 spl_autoload_register('load_class');
function load_class($classname) {     $filename = "./class/".$classname.".class.php";     if (is_file($filename))     {         include $filename;     } }

 

使用spl_autoload_register()的好处是不可言喻的: (1)自动加载对象更加方便,很多框架都是这样做的:

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)你要知道__autoload()函数只能存在一次啊,spl_autoload_register()当然能注册多个函数

 

function a () {      include 'a.php'; }  function b () {      include 'b.php'; }  spl_autoload_register('a');  spl_autoload_register('b'); 

 

(3)SPL函数很丰富,提供了更多功能,如spl_autoload_unregister()注销已经注册的函数、spl_autoload_functions()返回所有已经注册的函数等。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn