spl_autoload_register的使用以及示例

spl_autoload_register 函数的功能就是把传入的函数(参数可以为回调函数或函数名称形式)注册到 SPL __autoload 函数队列中,并移除系统默认的 __autoload() 函数。

一旦调用 spl_autoload_register() 函数,当调用未定义类时,系统就会按顺序调用注册到 spl_autoload_register() 函数的所有函数,而不是自动调用 __autoload() 函数。

 

1.自动加载类注册页面 

<?php
namespace Application\Autoload;

class Loader
{
    const UNABLE_TO_LOAD = '文件加载失败:';
    static $dirs = [];
    static $registered = 0;

    public static function autoLoad($class)
    {
        $success = false;
        $fn = str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
        foreach (self::$dirs as $start) {
            $file = $start . DIRECTORY_SEPARATOR . $fn;
            if (self::loadFile($file)) {
                $success = true;
                break;
            }
        }
        if (!$success) {
            if (!self::loadFile(__DIR__ . DIRECTORY_SEPARATOR . $fn)) {
                throw new \Exception(self::UNABLE_TO_LOAD . '' . $class);
            }
        }
        return $success;

    }

    public static function loadFile($file)
    {
        if (file_exists($file)) {
            require_once $file;
            return true;
        }
        return false;
    }

    public static function addDirs($dirs)
    {
        if (is_array($dirs)) {
            self::$dirs = array_merge(self::$dirs, $dirs);
        } else {
            self::$dirs[] = $dirs;
        }
    }

    public static function init($dirs = [])
    {
        if ($dirs) {
            self::addDirs($dirs);
        }
        if (self::$registered == 0) {
            spl_autoload_register(__CLASS__ . '::autoload');
            self::$registered++;
        }
    }

    public function __construct($dirs=[])
    {
        self::init($dirs);
    }

}

2.测试类页面 

  

<?php
namespace Application\test;

class TestClass
{
    public function getTest(){
        return __METHOD__;
    }


}

 

3. 运行测试页面 

  

<?php
/**
 * Create by ZhangShuo
 * When you read this code, good luck for you.
 */
$S=__DIR__;
require __DIR__.'/../Autoload/Loader.php';
Application\Autoload\Loader::init(__DIR__.'/../..');
$test=new Application\test\TestClass();
echo $test->getTest();


$fake=new Application\test\FakeClass();
echo $fake->getTest();

4. 输出页面 

 

posted @ 2021-07-02 17:00  飘柔2019  阅读(659)  评论(0编辑  收藏  举报