Search code examples
phpclassnamespacesautoloadspl-autoload-register

How to check if Autoload loads only used classes?


Uisng spl_autoload_register for auto loading classes on my code. Example:

<?php    
spl_autoload_register(function ($class_name) { 
    include 'my_class1.php';
    include 'my_class2.php';
    //...
    include 'my_classN.php';
});

$obj = new MyClass1();
?>

What if I used just class MyClass1 in my code, does autoload loads all files or just my_class1.php? Thanks in advance.

EDIT: DO NOT use above code. Now I using @Alex Howansky's code with PSR-4 autoloading specifications.

NOTE: Autoload requires to use namespaces if classes located in subdirectory relatively to basedir (see examples).


Solution

  • With this code, the first time you refer to any class, it will load every class. This will work, but almost certainly isn't what you want. In an autoloader, you usually just want to load only the one source file containing the one class referenced by $class_name. Something like this:

    spl_autoload_register(function ($class_name) {
        $filename = '/path/to/classes/' . $class_name . '.php';
        require_once $filename;
    });
    

    This obviously becomes very difficult if your source file names don't match your class names or you otherwise can't determine the source file names based on the class names. This is why you should use PSR-4 naming conventions.