Skip to content
Advertisement

PHP autoload with namespaces do not load file

I have an issue with my autoloader and namespaces. Below the autoloader

<?php
spl_autoload_register( function( $class ) {

    $folder = 'include/';
    $prefix = 'class.';
    $ext    = '.php';
    
    $fullPath = $folder . $prefix . $class . $ext;
  
    if( !file_exists( $fullPath ) ){
        print 'Class file not found!';
        return false;
    }

    require_once $fullPath;
});
?>

Below the index file

<?php
require 'autoload.php';
//use backslash for namespace
$pers = new PersonPerson();
?>

The file for the class Person is saved in the directory root->include->Person I used the namespace in the class file like this

<?php
namespace Person;

class Person{
    function __construct(){
        print 'autoload works';
    }
}
?>

If I visit the index file in the browser it returns ‘Class file not found’. Do I use the namespace correctly?

Advertisement

Answer

Change your autoload code a little

<?php
spl_autoload_register( function( $class ) {

    $folder = 'include/';
    $prefix = '.class';
    $ext    = '.php';
    //replace the backslash 
    $fullPath = $folder . str_replace( "\", '/', $class ) . $prefix . $ext;

    if( !file_exists( $fullPath ) ){
        print 'Class file not found!';
        return false;
    }
    
    require_once $fullPath;
});
?>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement