2013-04-18 155 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。該包提供更多的功能,如多個包含路徑,路徑前綴和靜態自動加載(使用預定義的關聯數組類名=>文件名)。你可以使用它,如果你喜歡;)