2016-09-29 21 views
2

我們以前只包含存儲在{project_root}/includes文件夾中的類。我們使用自動加載功能在我們的應用程序中包含我們需要的類。現在,我想用一些圖書館,我面臨着一個問題:PHP無法自動載入類

1)自動加載:

// {project_root}/includes/autoLoad.php 
// There is a global_connfig.php file that loads by directive in php.ini 
// auto_prepend_file = /var/www/global_config.php which includes autoload.php file and sets the include path to {project_root}/includes 
function __autoload($classname){ 
    include "$classname.php"; 
} 

2)的代碼,我想用:

//just an example from the monolog reference 
// I put Monolog folder with it's subfolders in {project_root}/includes 
use Monolog\Logger; 
use Monolog\Handler\StreamHandler; 

$log = new Logger("name"); 
$log->pushHandler(new StreamHandler(LOGSPATH . '/monolog', Logger::WARNING)); 


$log->warning('Foo'); 
$log->error('Bar'); 

3)錯誤:

Warning: include(Monolog\Logger.php): failed to open stream: No such file or 
directory in {project_root}/includes/autoLoad.php 

我試着用這樣的東西:autoloading classes in subfolders,但仍然得到 Class 'Monolog\Logger' not found

問題更新

+0

哪裏是你的自動加載功能註冊?您是否嘗試過「include _ _ DIR _ _。」/ $ classname.php「;? – Thibault

+0

在您要使用的代碼中,哪裏包含includes/autoLoad.php? – Thibault

+0

您是否有Monolog \ Logger類的某處在你的include_path中? – Thibault

回答

1

試試這個自動加載函數:

function __autoload($classname) 
{          
    $filename = str_replace("\\", "/", $classname).".php";  
    include __DIR__."/$filename";          
} 
  • 它取代\/匹配路徑
  • 它從includes/目錄搜索。

你也可以考慮加入includes/路徑您include_path PHP指令:

set_include_path(get_include_path() . PATH_SEPARATOR . "{project_root}/includes"); 
+0

Woww,那看起來去除我得到的錯誤!現在它只是'警告:包括{project_root} /includes/Psr/Log/LoggerInterface.php):'但這是在一個Monolog中,所以現在它創建了Monolog。 THA NKS! – Daria

+1

這裏不需要'preg_replace()'。 'str_replace()'也可以完成這項工作,速度更快。我還建議使用'spl_autoload_register()'而不是'__autoload()'。 – simon

+1

嘗試它時我有同樣的錯誤。這是因爲Monolog依賴於Psr。查看Monolog的composer.json。你需要Psr。或者使用作曲家來包含Monolog及其依賴關係,這會有很大的幫助。 – Thibault