George Newton
George Newton

Reputation: 3293

Why use an autoloader class over autoloader functions?

PHP has a built-in autoloader register, spl_autoloader_register(), where you can write your own autoloader functions, like I did below (any improvisations you can think of would be helpful):

<?php

require_once(__DIR__ . '/../libraries/global.lib.php');

            function load_classes($class) { // appears to get all the names of the classes that are needed in this script...
              $file_name = __DIR__ . '/classes/' . $class . '.class.php';
              if (file_exists($file_name)) {
                require_once($file_name);
              }
            }

            function load_interfaces($interface) {
              $file_name = __DIR__ . '/classes/' . $interface . '.interface.php';
              if (file_exists($file_name)) {
                require_once($file_name);
              }
            }

            spl_autoload_register('load_interfaces');
            spl_autoload_register('load_classes');

?>

But I started looking at other code and saw that people use an autoloader class instead of the built-in PHP autoloader functions: why is this?

Upvotes: 1

Views: 133

Answers (1)

Nico
Nico

Reputation: 2663

From the PHP documentation on autoloading:

Tip spl_autoload_register() provides a more flexible alternative for autoloading classes. For this reason, using __autoload() is discouraged and may be deprecated or removed in the future.

So the answer is actually that you're doing it the recommended way. The code you're looking at may be legacy, since __autoload() was available before spl_autoload_register().

Note that you can also use static class functions for autoloading, if you want to go OO as much as possible:

class MyClass {
    static function myloader($name) {
        require_once($name.'.php');
    }
}
spl_autoload_register('MyClass::myloader');

Upvotes: 3

Related Questions