Search code examples
phpautoloadspl

PHP spl_autoload_register() flavors advantages/disadvantages


The spl_autoload_register() function can be used with 3 types of callbacks: functions, static methods and regular methods. Are there any advantages/disadvantages for these 3 types compared to each other?


Solution

  • Not really any major differences.

    A closure (defined like the following (PHP 5.3+ only)) can never be unregistered, unless it is saved to a variable:

    spl_autoload_register(function($class) { ... });
    

    A static method can actually auto load the static class before running its autoloader

    spl_autoload_register(function($class) {
        if ($class === 'AutoLoader') {
            var_dump('Auto loading AutoLoader');
            class AutoLoader {
                public static function autoload($class) {
                    var_dump(__CLASS__ . ' is loading: ' . $class);
                }
            }
        }
    });
    
    spl_autoload_register('AutoLoader::autoload');
    
    Test::func();
    
    // 'Auto loading AutoLoader'
    // 'AutoLoader is loading: Test'
    

    Although, I dont know why you would want to do that.

    Static calls are easier to unregister though.

    Either way you should follow the PSR0 auto loading standards: https://gist.github.com/221634