加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 17:09:11 所属栏目:PHP教程 来源:网络整理
导读:这是我的自动装载机课程.我从本周开始学习 PHP.我从不同的文章和 PHP动作书中得到了自动加载器的想法,但我不知道它实际上是如何运作的? class autoloader { public static $loader; public static function init() { if(self::$loader == NULL) { self::$lo
这是我的自动装载机课程.我从本周开始学习 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读