Aurel
Aurel

Reputation: 1

PHP Namespaces autoload

I have the following directory structure:
/var/www/Project1/Project1.php
/var/www/Project1/User/UserProfile.php
Inside Project1.php:

<?php
namespace Project1;
set_include_path( __DIR__ );
spl_autoload_extensions('.php');
spl_autoload_register();

use User\UserProfile;

$u = new Avatar();
...

?>

Inside UserProfile.php:

<?php    
namespace Project1\User;
class Avatar{
}
...
?>

When I execute php Project1.php I get:

PHP Fatal error: spl_autoload9(): Class User\UserProfile could not be loaded

I don't see the problem.

Upvotes: 0

Views: 981

Answers (1)

hek2mgl
hek2mgl

Reputation: 158260

spl_autoload_register(); when called with no params will just register the default autoloader which fails to handle namespaces with your project layout. You'll have to register your own method to make it work. Like this:

spl_autoload_register('my_autoload');

And here comes the autoload function. This function expects the classes to be stored in a way like:

/path/to/project/Namespace/Classname.php
/path/to/project/Namespace/Subnamespace/Classname.php

You can name the classes like \Namespaces\Classname or the old style way Namespace_Classname:

function my_autoload ($classname) {
    // if the class where already loaded. should not happen
    if (class_exists($classname)) {
        return true;
    }   

    // Works for PEAR style class names and namespaced class names
    $path = str_replace(
        array('_', '\\'),
        '/',
        $classname
    ) . '.php';

   if (file_exists('/path/to/project/' . $tail)) {
        include_once 'path/to/project/' . $tail;
        return true;
    }   

    return false;
}   

Note that the function is taken from my github package Jm_Autoloader. The package provides more functionality as multiple include paths, path prefixes and static autoloading (with a predefined assoc array class name => file name). You can use it if you like ;)

Upvotes: 1

Related Questions