如何在不使用__autoload()的情况下使用spl_autoload() [英] How to use spl_autoload() as __autoload() goes DEPRECATED

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

问题描述

根据 http://php.net/manual/zh-CN/language. oop5.autoload.php 魔术函数__autoload()在即将发布的PHP版本中将被弃用和删除(!).官方的替代方法是spl_autoload().参见 http://www.php.net/manual/zh/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.

我的问题:如何替换它(我的自动类自动加载器)

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

具有spl_autoload()版本的问题?问题是:我不知道如何为该函数提供路径(它仅接受名称空间).

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

顺便说一句:SO.com上有很多与此主题相关的主题,但是没有一个主题清晰明了&.一个简单的解决方案,取代了我那性感的单线.

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.

推荐答案

您需要使用可调用" .从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.

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

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