您的位置:首页 > 编程语言 > PHP开发

PHP类的自动加载__autoload && spl_autoload_register

2011-06-24 16:11 741 查看
PHP类的自动加载__autoload && spl_autoload_register

通常我们写一个类如下:

a.php

class A
{
public function __construct()
{
echo "hello world!";
}
}
[/code]
page.php

require("a.php");
$a = new A();
[/code]
我们是通过手工引用某个类的文件来实现函数或者类的加载

但是当系统比较庞大,以及这些类的文件很多的时候,这种方式就显得非常不方便了

于是PHP5提供了一个::auotload::的方法

我们可通过编写该方法来自动加载当前文件中使用的类文件

page.php

function __autoload($classname)
{
$class_file = strtolower($classname).".php";
if (file_exists($class_file)){
require_once($class_file);
}
}

$a = new A();
[/code]
这样,当使用类A的时候,发现当前文件中没有定义A,则会执行autoload函数,并根据该函数实现的方式,去加载包含A类的文件

同时,我们可以不使用该方法,而是使用我们自定义的方法来加载文件,这里就需要使用到函数

bool spl_autoload_register ( [callback $autoload_function] )

page.php

function my_own_loader($classname)
{
$class_file = strtolower($classname).".php";
if (file_exists($class_file)){
require_once($class_file);
}
}

spl_autoload_register("my_own_loader");

$a = new A();
[/code]
实现的是同样的功能

自定义的加载函数还可以是类的方法

class Loader
{
public static function my_own_loader($classname)
{
$class_file = strtolower($classname).".php";
if (file_exists($class_file)){
require_once($class_file);
}
}
}

// 通过数组的形式传递类和方法的名称
spl_autoload_register(array("my_own_loader","Loader"));

$a = new A();
[/code]
转自:http://www.emptykid.com/blog/archives/151

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息