2013-04-18 96 views
0

我有以下目录结构:
/var/www/Project1/Project1.php
/var/www/Project1/User/UserProfile.php
内Project1.php:
PHP命名空间自动加载

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

use User\UserProfile; 

$u = new Avatar(); 
... 

?> 

内UserProfile.php:

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

当我执行php Project1.php我得到:

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

我没有看到问题。

回答

1

spl_autoload_register();当没有参数调用时,只会注册默认的自动加载器,无法处理名称空间与您的项目布局。你必须注册自己的方法才能使其工作。像这样:

spl_autoload_register('my_autoload'); 

这里是自动装载功能。该功能预计类存储的方式,如:

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

可以命名像\Namespaces\Classname或旧式方式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; 
} 

注意,功能是从我的github上取包Jm_Autoloader。该包提供更多的功能,如多个包含路径,路径前缀和静态自动加载(使用预定义的关联数组类名=>文件名)。你可以使用它,如果你喜欢;)