0

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.

1 Answer 1

1

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 ;)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.