简体   繁体   中英

How to use spl_autoload() instead of __autoload()

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.

: How to replace this (my automatic class autoloader) with a version with spl_autoload() ?:如何用带有spl_autoload()的版本替换这个(我的自动类自动加载器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).

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.

You need to register autoload functions withspl_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';
});

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 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM