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

php 自动加载类函数spl_autoload_register()

2016-02-18 09:45 591 查看
php手册已经建议使用该函数spl_autoload_register(),而不再建议使用魔术方法__autoload(),这里也只做spl_autoload_register()解释。文档中描述的是spl_autoload_register()可以进行多个解释,而__atuoload()只是一个。

If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once.

spl_autoload_register 可以很好地处理需要多个加载器的情况,这种情况下 spl_autoload_register 会按顺序依次调用之前注册过的加载器。作为对比, __autoload 因为是一个函数,所以只能被定义一次。

spl_autoload_register()函数可以直接加载一个自定义函数用于引入类文件进行类查找,也可以以数组的形式加载一个类里面的静态加载类文件方法。

加载自定义类的静态方法

class LOAD {
//必须传入类名,与文件名/类名称一致
static function loadclass($class) {
// 该处可以自定义加载的路径
$file = $class.'.class.php';
if (is_file($file)) {
require_once($file);
}
}
}
/* 未找到未定义类时调用 */
spl_autoload_register(array('LOAD', 'loadclass'));
//例子
$view = new Test; //当初始化时会自动去寻找文件里面的Test
echo $view::test1();


直接加载

function load_class($class) {
$file = $class.'.class.php';
if (is_file($file)) {
require_once($file);
}
}
/* 未找到未定义类时调用 */
spl_autoload_register('load_class');
$view = new Test;
echo $view::test1();


另外,给出另一个类文件Test.class.php

<?php
class Test {
public static function test1() {
echo 1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: