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");
我们过去只包含存储在 {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");