【发布时间】:2014-04-16 11:03:30
【问题描述】:
我正在摆弄自动加载,并尝试创建一个符合 PSR-0 标准的文件结构。但是我收到了这个错误:
Warning: require(GetMatchHistory\api.php): failed to open stream: No such file or directory in C:\xampp\htdocs\Test\Test.php on line 15
Fatal error: require(): Failed opening required 'GetMatchHistory\api.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\Test\Test.php on line 15
这是我的文件结构:
我正在使用带有这个自动加载功能的测试 PHP:
function autoload($className)
{
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strrpos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
require $fileName;
}
spl_autoload_register('autoload');
$Query = new GetMatchHistory_api();
此函数是从建议的 PSR-0 函数 here 复制粘贴的
我是否误解了结构应该如何? “api.php”中的类是GetMatchHistory_api
编辑:另一个问题
我使用了 MrCode 建议的答案,但是现在我遇到了一个问题,即自动加载器无法加载另一个目录中的类。
use Classes\Queries\History\GetMatchHistoryAPI;
use Classes\Queries\History\GetMatchHistoryBASE;
use Classes\Utilities\send;
当我从GetMatchHistoryAPI 内部的函数中调用send 类时,我收到错误:
Warning: require(Classes\Queries\History\send.php): failed to open stream: No such file or directory in C:\xampp\htdocs\Test\Test.php on line 15
但是,从上图可以看出,发送类不在该文件路径中。为什么会出现这个错误?
【问题讨论】:
-
您不应该要求一个不存在的文件。那么仍然是一个致命错误,但是因为找不到该类,而不是因为失败的要求。细节,但更清楚。
-
@Rudie 我看到该文件在该目录中不存在。但是我不确定为什么会这样。如果按照上面的代码,我输入
$Query = new send(),则该文件在正确的位置“找到”(对不起,术语不好),但当send类从另一个类执行时不是。 -
我知道。我实际上并没有评论这个问题,对不起。致命错误应该是“未找到 X 类”,而不是“无法包含文件 Y”。根本没有帮助你,但它更“正确”。
标签: php namespaces autoload psr-0