php 如何使用 spl_autoload() 作为 __autoload() 已弃用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10687804/
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() as __autoload() goes DEPRECATED
提问by Sliq
According to http://php.net/manual/en/language.oop5.autoload.phpthe magic function __autoload() will become DEPRECATED and DELETED (!) in upcoming PHP versions. The official alternative is spl_autoload(). See http://www.php.net/manual/en/function.spl-autoload.php. But the php manual does not explain the proper use of this baby.
根据http://php.net/manual/en/language.oop5.autoload.php魔术函数 __autoload() 将在即将推出的 PHP 版本中被弃用和删除(!)。官方的替代方法是 spl_autoload()。请参阅http://www.php.net/manual/en/function.spl-autoload.php。但是php手册并没有说明这个宝贝的正确使用方法。
My question: How to replace this (my automatic class autoloader)
我的问题:如何替换这个(我的自动类自动加载器)
function __autoload($class) {
include 'classes/' . $class . '.class.php';
}
with a version with spl_autoload() ?Problem is: I cannot figure out how to give that function a path (it only accepts namespaces).
带有 spl_autoload() 的版本?问题是:我无法弄清楚如何为该函数提供路径(它只接受命名空间)。
By the way: There are a lot of threads regarding this topic here on SO.com, but none gives a clean & simple solution that replaces my sexy one-liner.
顺便说一句:在 SO.com 上有很多关于这个主题的主题,但没有一个提供干净简单的解决方案来取代我性感的单线。
回答by lonesomeday
You need to register autoload functions with spl_autoload_register. You need to provide a "callable". The nicest way of doing this, from 5.3 onwards, is with an anonymous function:
您需要使用spl_autoload_register. 您需要提供一个“可调用的”。从 5.3 开始,最好的方法是使用匿名函数:
spl_autoload_register(function($class) {
include 'classes/' . $class . '.class.php';
});
The principal advantage of this against __autoloadis of course that you can call spl_autoload_registermultiple times, whereas __autoload(like any function) can only be defined once. If you have modular code, this would be a significant drawback.
这样做的主要优点__autoload当然是您可以spl_autoload_register多次调用,而__autoload(像任何函数一样)只能定义一次。如果您有模块化代码,这将是一个重大缺点。
2018 update to this: there shouldn't really be that many occasions when you needto roll your own autoloader. There is a widely accepted standard (called PSR-4) and several conforming implementations. The obvious way of doing this is using Composer.
2018 年对此的更新:当您需要推出自己的自动装载机时,真的不应该有那么多场合。有一个广泛接受的标准(称为PSR-4)和几个符合标准的实现。这样做的明显方法是使用Composer。

