如何使用spl_autoload_register? [英] How to use spl_autoload_register?

查看:80
本文介绍了如何使用spl_autoload_register?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Manage
{

spl_autoload_register(function($class) {
    include $class . '.class.php';
});
}

说我有一些上面的代码.我选择使用加载类的匿名函数方法,但是如何使用呢?它究竟如何确定要加载哪个'$class'?

Say I have some code like the above. I chose to use the anonymous function method of loading classes, but how is this used? How exactly does it determine which '$class' to load?

推荐答案

您不能在此处放置代码.您应该在课程之后添加SPL寄存器.如果要在Manage类中注册函数,可以执行以下操作:

You can't put the code there. You should add the SPL register after your class. If you wanted to register a function inside the Manage class you could do:

class Manage {
    public static function autoload($class) {
        include $class . '.class.php';
    }
}

spl_autoload_register(array('Manage', 'autoload'));

但是,正如您所演示的,您可以使用匿名函数.您甚至都不需要上课,所以您可以这样做:

However, as you demonstrated you can use an anonymous function. You don't even need a class, so you can just do:

spl_autoload_register(function($class) {
    include $class . '.class.php';
});

无论哪种方式,您指定的功能都会添加到负责自动加载的功能池中.您的函数将附加到此列表中(因此,如果列表中已经有任何函数,则您的函数将排在最后).这样,当您执行以下操作时:

Either way, the function you specify is added to a pool of functions that are responsible for autoloading. Your function is appended to this list (so if there were any in the list already, yours will be last). With this, when you do something like this:

UnloadedClass::someFunc('stuff');

PHP将意识到尚​​未声明UnloadedClass.然后它将遍历SPL自动加载功能列表.它将使用一个参数调用每个函数:'UnloadedClass'.然后,在调用每个函数之后,它将检查该类是否存在.如果没有,它将一直持续到列表末尾.如果该类从未加载过,则会出现致命错误,告诉您该类不存在.

PHP will realize that UnloadedClass hasn't been declared yet. It will then iterate through the SPL autoload function list. It will call each function with one argument: 'UnloadedClass'. Then after each function is called, it checks if the class exists yet. If it doesn't it continues until it reaches the end of the list. If the class is never loaded, you will get a fatal error telling you that the class doesn't exist.

这篇关于如何使用spl_autoload_register?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆