Search code examples
phpsyntaxpsr-0

How to write this autoloader PSR-0/1/2 save?


The PSR-0/1/2-syntax checker on phphint.org gives this message

The first parameter of a multi-line function declaration must be on
the line after the opening bracket 

on this code:

// class autoloader for PHP 5.3+
spl_autoload_register( function ($class) {
    include('classes/' . $class . '.class.php');
});

I tried a lot, but never got this little piece of code PSR-0/1/2-save. How would a solution look like (or is the analyzer on phphint too strict ?) ?


Solution

  • I fixed this by myself, but the solution is extremely ugly.

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

    Maybe the PSR-guys should think about their weird syntax. The correct solution looks like this, even if it is a step backwards.

    // autoload function (it's NOT "__autoload", __autoload is
    // DEPRECATED since PHP 5.4!)
    function autoload($class) {
        include('classes/' . $class . '.class.php');
    }
    
    // class autoloader for PHP 5.3+, registers the function that's used if a class/file
    // is not found (=autoloader)
    spl_autoload_register('autoload');