php – 这个自动加载功能如何?

这是我的自动装载机课程.我从本周开始学习PHP.我从不同的文章PHP动作书中得到了自动加载器的想法,但我不知道它实际上是如何运作的?

class autoloader {
    public static $loader;

    public static function init()
    {
        if(self::$loader == NULL) {
            self::$loader = new self();
        }
        return self::$loader;
    }   

    public function __construct()
    {
        spl_autoload_register(array(this, 'library'));
        spl_autoload_register(array(this, 'controller'));
        spl_autoload_register(array(this, 'helper'));
        spl_autoload_register(array($this, 'model'));
    }

    public function library($class) 
    {
        set_include_path(get_include_path() . PATH_SEParaTOR . '/lib');
        spl_autoload_extensions('.PHP');
        spl_autoload($class);
    }

    public function controller($class)
    {
        set_include_path(get_include_path() . PATH_SEParaTOR . '/controller');
        spl_autoload_extensions('.PHP');
        spl_autoload($class);
    }

    public function helper($class)
    {
        set_include_path(get_include_path() . PATH_SEParaTOR . '/helper');
        spl_autoload_extensions('.PHP');
        spl_autoload($class);
    }

    public function model($class)
    {
        set_include_path(get_include_path() . PATH_SEParaTOR . '/model');
        spl_autoload_extensions('.PHP');
        spl_autoload($class);
    }
}

我想问一下这款自动加载器的功能究竟如何?
例如,如果我实现了一个位于lobrary文件夹下的类
如何处理这个完整的文件

解决方法:

首先,当您实例化一个类时,它的构造函数注册四个函数来处理类自动加载.

$autoloader = new autoloader();

他们每个人都会在自己的特定目录中查找文件.无需调用autoloader :: init()函数,因为所有自动加载函数都已通过实例化类注册.

然后,当你尝试实例化一个类时,如果PHP无法找到它,那么在失败之前它将运行函数,由spl_autoload_register()按照它们注册的顺序注册. (autoloader :: library(),autoloader :: controller(),autoloader :: helper()和autoloader :: model()),如果在该类可用之后,它将被实例化.

扩展您的示例,这里是一些代码片段:

<?PHP
include 'autoloader.PHP'; // in this file we have our autoloader class

$autoloader = new autoloader();

$libClass = new someLib();

当我们调用new someLib()时,PHP自动加载机制将在include_path指令中提到的所有区域中查找文件’somelib.PHP'(!lowercase!).你看,每个函数都为这个指令添加了自己的位置

set_include_path(get_include_path() . PATH_SEParaTOR . '/controller');

这意味着名为“controller”的文件夹(位于根目录中)将添加到include_path中,然后spl_autoload()将在其中查找文件.所以你必须创建文件/lib/somelib.PHP并拥有一个名为’someLib’的类

希望这可以帮助

补充阅读:
spl_autoload_register
spl_autoload

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...