簡體   English   中英

PHP 無法自動加載類

[英]PHP cannot autoload classes

我們過去只包含存儲在{project_root}/includes文件夾中的類。 我們使用自動加載功能在我們的應用程序中包含我們需要的類。 現在我想使用一些庫,但遇到了一個問題:

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

問題已更新

試試這個自動加載功能:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM