如何使用 spl_autoload() 而不是 __autoload() [英] How to use spl_autoload() instead of __autoload()

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

问题描述

根据http://php.net/manual/en/language.oop5.autoload.php 魔法函数 __autoload() 在即将到来的 PHP 版本中将成为 DEPRECATEDDELETED (!).官方的替代方法是 spl_autoload().参见 http://www.php.net/manual/en/function.spl-autoload.php.但是PHP手册并没有说明这个宝贝的正确使用方法.

According to http://php.net/manual/en/language.oop5.autoload.php the 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.

我的问题:如何用带有 spl_autoload() 的版本替换这个(我的自动类自动加载器)?

My question: How to replace this (my automatic class autoloader) with a version with spl_autoload()?

function __autoload($class) {
    include 'classes/' . $class . '.class.php';
}

问题:我不知道如何为该函数指定路径(它只接受命名空间).

Problem: I cannot figure out how to give that function a path (it only accepts namespaces).

顺便说一下,SO 上有很多关于这个主题的主题,但没有一个提供干净的 &简单的解决方案,取代了我性感的单衬.

By the way, there are a lot of threads regarding this topic here on SO, but none gives a clean & simple solution that replaces my sexy one-liner.

推荐答案

您需要使用 spl_autoload_register.您需要提供 "callable".从 5.3 开始,最好的方法是使用匿名函数:

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(function($class) {
    include 'classes/' . $class . '.class.php';
});

这相对于 __autoload 的主要优点当然是您可以多次调用 spl_autoload_register,而 __autoload(像任何函数一样)可以只能定义一次.如果您有模块化代码,这将是一个重大缺陷.

The principal advantage of this against __autoload is of course that you can call spl_autoload_register multiple times, whereas __autoload (like any function) can only be defined once. If you have modular code, this would be a significant drawback.

2018 年更新:您需要推出自己的自动加载器的情况真的不应该太多.有一个被广泛接受的标准(称为 PSR-4)和几个符合标准的实现.这样做的明显方法是使用 Composer.

2018 update to this: there shouldn't really be that many occasions when you need to 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.

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

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