繁体   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