2

我正在摆弄自动加载,并试图制作一个符合 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 函数复制粘贴的

我对结构应该如何有误解吗?“api.php”中的类是GetMatchHistory_api

编辑:另一个问题

我已经使用了 MrCode 建议的答案,但是现在我遇到了一个问题,即自动加载器不会加载另一个目录中的类。

use Classes\Queries\History\GetMatchHistoryAPI;
use Classes\Queries\History\GetMatchHistoryBASE;
use Classes\Utilities\send;

当我send从里面的函数调用类时GetMatchHistoryAPI,我收到错误:

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

但是,从上图中可以看出,发送类不在该文件路径中。为什么会出现这个错误?

4

1 回答 1

2

基于该结构,您需要将类重命名为Classes_Queries_GetMatchHistory_api并将实例化它的代码更改为:

$Query = new Classes_Queries_GetMatchHistory_api();

原因是您Test.php位于根目录中,而 api 类位于目录中Classes/Queries/GetMatchHistory


使用命名空间而不是下划线方法的示例:

api.php:

namespace Classes\Queries\GetMatchHistory;

class api
{

}

测试.php:

spl_autoload_register('autoload');
$Query = new Classes\Queries\GetMatchHistory\api();

或使用use

use Classes\Queries\GetMatchHistory\api;

spl_autoload_register('autoload');
$Query = new api();

要解决您的评论:

我将有相同的类名,但在不同的文件夹下(所以 GetMatchHistory - api.php 和 GetMatchDetails - api.php)。我想这会在调用类时变得太模棱两可了

命名空间旨在解决这个问题。命名空间允许您拥有同名的类(但在不同的命名空间中)并避免任何冲突。

例如,您在 和 下都有一个api类。GetMatchHistoryGetMatchDetails

文件:类/查询/GetMatchHistory/api.php

namespace Classes\Queries\GetMatchHistory;

class api
{
    public function __construct(){
        echo 'this is the GetMatchHistory api';
    }
}

文件:类/查询/GetMatchDetails/api.php

namespace Classes\Queries\GetMatchDetails;

class api
{
    public function __construct(){
        echo 'this is the GetMatchDetails api, I am separate to the other!';
    }
}

文件:Test.php(使用示例)

spl_autoload_register('autoload');

$historyApi = new Classes\Queries\GetMatchHistory\api();
$detailsApi = new Classes\Queries\GetMatchDetails\api();

如果你愿意,你可以给一个别名而不是输入整个完全限定的命名空间:

use Classes\Queries\GetMatchHistory\api as HistoryApi;
use Classes\Queries\GetMatchDetails\api as DetailsApi;

$historyApi = new HistoryApi();
$detailsApi = new DetailsApi();

如您所见,命名空间使多个具有相同名称的不同类成为可能,而不会发生冲突或使其模棱两可。

于 2014-03-12T11:42:55.027 回答