spl autoloading: Class is not found – namespace issue?

762 Views Asked by At

I am just getting my feet wet with PHP autoloading. I actually think I got the basics down, but somehow it still won't work.

I got the following directory structure:

myLib
    -bootstrap.php
    -sven
        -project
            project.php

bootstrap.php is the file that will be included to use the lib. In this file, I simply have the following code:

spl_autoload_extensions('.php');
spl_autoload_register();

$var = new \sven\project\project();
$var->init();

And in project.php:

namespace sven\project;

class project {
    public function init() {
        echo 'It works!';
    }
}

The way the autoloader is used, to my understanding, the core PHP autoloader should translate the namespace into directories and then look for a php containing the class.

Instead of displaying 'It works!', a fatal error is thrown. Unfortunately, I can't exactly tell what that error is because the CMS only informs me that there was a fatal error.
But with such a simple structure, I am sure the error is pretty basic and easy to find for someone who knows how it works.

Where am I going wrong with this example – did I correctly describe how the autoloader should work in this setup or is there a misunderstanding?

EDIT: Finally got the error log running:

Fatal error: Class undefined: sven\\project\\project\\project\\project in /xxx/bootstrap.php on line 36

That obviously looks wrong, but how to change that? Why are there two backslashes?

2

There are 2 best solutions below

1
DarkChipolata On
spl_autoload_extensions('.php');
spl_autoload_register();

This code works only with PHP 5.3 and above.

0
Paul Dumitru On

Sven,

I just answered another question about spl_autoload, try my example click here

I hope it helps!

PS: Also don't just autoload all .php files on your path , that can be dangerous !