php 如何使用 spl_autoload_register?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11131238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use spl_autoload_register?
提问by Steve
class Manage
{
spl_autoload_register(function($class) {
include $class . '.class.php';
});
}
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?
假设我有一些类似上面的代码。我选择使用匿名函数加载类的方法,但是这个怎么用呢?它究竟是如何确定'$class'加载哪个的?
回答by Bailey Parker
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 Manageclass you could do:
你不能把代码放在那里。您应该在课后添加 SPL 寄存器。如果你想在Manage类中注册一个函数,你可以这样做:
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 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.
PHP 会意识到 UnloadedClass 还没有被声明。然后它将遍历 SPL 自动加载函数列表。它将使用一个参数调用每个函数:'UnloadedClass'。然后在调用每个函数后,它会检查该类是否存在。如果不是,它会继续直到到达列表的末尾。如果从未加载该类,您将收到一个致命错误,告诉您该类不存在。
回答by zerkms
How exactly does it determine which '$class' to load?
它究竟如何确定要加载哪个“$class”?
The $classis passed by php automatically. And it's the name of the class not declared yet, but used somewhere in runtime
该$class是由PHP自动传递。它是尚未声明的类的名称,但在运行时的某处使用

