2015-05-30 47 views
2

我想自動載入類,但spl_autoload寄存器沒有找到該文件,我收到文件未找到錯誤。Spl_autoload_register文件未找到

我的文件結構:

index.php 
system/ 
    configs/ 
     config.php 
    messages/ 
     message.php 
    user/ 
     user.php 

因此,這裏是我在做什麼。

的config.php

我從另一個答案了以下功能

spl_autoload_register(function ($className) { 

# Usually I would just concatenate directly to $file variable below 
# this is just for easy viewing on Stack Overflow) 
    $ds = DIRECTORY_SEPARATOR; 
    $dir = __DIR__; 

// replace namespace separator with directory separator (prolly not required) 
    $className = str_replace('\\', $ds, $className); 

// get full name of file containing the required class 
    $file = "{$dir}{$ds}{$className}.php"; 

    require_once $file; 
}); 

use system\user\user; 

$obj = new User(); 

user.php的

namespace system\user; 
class user{ 
    ... 
} 

我收到以下錯誤:

Fatal error: require_once(): Failed opening required 'C:\xampp\htdocs\System\Configs\System\User\User.php' (include_path='.;C:\xampp\php\PEAR') in 

任何幫助?

回答

0

更換

$file = "{$dir}{$ds}{$className}.php"; 

$file = "{$dir}/../../{$ds}{$className}.php"; 

讓你的根目錄爲system/,而不是system/configs/

+0

不起作用。 '警告:require_once(C:\ xampp \ htdocs \ System \ Configs /../../ \ System \ User \ Exception.php):未能打開流:沒有這樣的文件或目錄' – Magna

+0

'System \ User \ Exception .php'存在嗎? – Federkun

+0

我沒有那個文件 – Magna

0

您的文件是: 用戶/ user.php的

但您的自動加載器是外觀ing: User/User.php

這是因爲當你實例化$ obj = new User();那麼在自動加載器中您的$ className已成爲「用戶」。

更改: $ className = strtolower(str_replace('\',$ ds,$ className));

或更改目錄結構: 用戶/ user.php的

+0

這可能看起來很奇怪,但Windows不區分大小寫 – Federkun