PHP中spl_autoload_register函数的用法

 

view plaincopy to clipboardprint?
<?php   
class A   
{   
public function __construct()   
{   
echo 'Got it.';   
}   
}


然后我们有一个index.php需要用到这个类A,常规的写法就是

view plaincopy to clipboardprint?
<?php   
require('A.php');   
$a = new A();


但是有一个问题就是,假如我们的index.php需要包含的不只是类A,而是需要很多类,这样子就必须写很多行require语句,有时候也会让人觉得不爽。


不过在php5之后的版本,我们就不再需要这样做了。在php5中,试图使用尚未定义的类时会自动调用__autoload函数,所以我们可以通过编写__autoload函数来让php自动加载类,而不必写一个长长的包含文件列表。

例如在上面那个例子中,index.php可以这样写:

view plaincopy to clipboardprint?
<?php   
function __autoload($class)   
{   
$file = $class . '.php';   
if (is_file($file)) {   
require_once($file);   
}   
}   

$a = new A();

 

当然上面只是最简单的示范,__autoload只是去include_path寻找类文件并加载,我们可以根据自己的需要定义__autoload加载类的规则。

此外,假如我们不想自动加载的时候调用__autoload,而是调用我们自己的函数(或者类方法),我们可以使用spl_autoload_register来注册我们自己的autoload函数。它的函数原型如下:
bool spl_autoload_register ( [callback $autoload_function] )

我们继续改写上面那个例子:

view plaincopy to clipboardprint?
<?php   
function loader($class)   
{   
$file = $class . '.php';   
if (is_file($file)) {   
require_once($file);   
}   
}   

spl_autoload_register('loader');   

$a = new A();

 

这样子也是可以正常运行的,这时候php在寻找类的时候就没有调用__autoload而是调用我们自己定义的函数loader了。同样的道理,下面这种写法也是可以的:

view plaincopy to clipboardprint?
<?php   
class Loader   
{   
public static function loadClass($class)   
{   
$file = $class . '.php';   
if (is_file($file)) {   
require_once($file);   
}   
}   
}   

spl_autoload_register(array('Loader', 'loadClass'));   

$a = new A();

PHP培训笔记>>千锋php笔记

posted on 2017-06-07 10:02  帝都码农  阅读(78)  评论(0)    收藏  举报

导航