Search code examples
phpphp-8.1spl-autoload-register

PHP spl autoload classes not autoloading


I'm trying to use the SPL autoloader in php 8.1 but getting the bellow error.

PHP Parse error: syntax error, unexpected identifier "Router", expecting "{" in index.php on line 54

I have tested this in similar environments but on different versions of php and less than 8.1 all run perfectly fine. So the issue is unique to 8.1.

I can't seem to find anything other than the old autoloader function being depreciated on the docs which was to be replaced with spl.

I can't help but feel it's a syntax error specific to 8.1 and not actually anything to do with the spl autoloader. But again I've tried various things and just can't seem to get to the bottom of it.

Doe's anyone know of a specific reason why this may be happening?

Bellow is the code I'm using. Which again works in less than 8.

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

class Init {
    
    function __construct() {

        define( 'APPS_PATH', dirname( __FILE__ ) . '/' );
        
                // Get params
        $this->page = (isset($_GET['page'])) ? $_GET['page'] : 'Home';
        $this->action = (isset($_GET['page'])) ? $_GET['action'] : false;
            
    }
    
    public function get_page(){
        
        return $this->page;
        
    }
    
    public function get_action(){
        return $this->action;
    }

    public static function register() {
        spl_autoload_register( function ( $class ) {
            $class = str_replace( '\\', '/', $class );
            $class = str_replace( '/\s+/', '', $class );
            $file = APPS_PATH . $class . '.php';
            
            if ( file_exists( $file ) ) {
                // Check for Clas Introduction : echo '['.$file.']'.PHP_EOL;
                require_once ( $file );
                return true;
            }
            return false;
        } );
    }
    
}

$init = new Init();

$init->register();

// Routing to operation
use routing\ Router as Router;

$router = new Router();

$router->go_to_page($init->get_page());

Solution

  • You have extra space here:

    use routing\ Router as Router;
    

    It should be:

    use routing\Router as Router;
    

    This is a change in PHP 8 syntax:

    Namespaced names can no longer contain whitespace: While Foo\Bar will be recognized as a namespaced name, Foo \ Bar will not. Conversely, reserved keywords are now permitted as namespace segments, which may also change the interpretation of code: new\x is now the same as constant('new\x'), not new \x().

    (ref)