How to use spl_autoload () since __autoload () is sent DEPRECATED

According to http://php.net/manual/en/language.oop5.autoload.php the magic function __autoload () will become DEPRECATED and DELETED (!) In future versions of PHP. The official alternative is spl_autoload (). See http://www.php.net/manual/en/function.spl-autoload.php . But, as usual, the php manual sucks in like hell and does not explain the proper use of this child.

My question is: how to replace this (my automatic class autoloader)

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

with version with spl_autoload ()? The problem is this: I cannot figure out how to pass this function to the path (it only accepts namespaces).

By the way, there are many topics on SO.com related to this topic, but none of them provide a clean and simple solution that replaces my sexy single-line font.
+5
source share
1 answer

You need to register startup features spl_autoload_register. You need to provide a "callable" . The most enjoyable way to do this, starting at 5.3, is with an anonymous function:

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

The main advantage of this method against __autoloadis, of course, multiple calls spl_autoload_register, while __autoload(like any function) can be defined only once. If you have modular code, this will be a significant drawback.


2018 : , . (PSR-4) . Composer.

+11

All Articles