PHP致命错误:加载URL时找不到类


PHP Fatal Error: Class not found when loading URL

我正在编码的web服务中有一个奇怪的错误。当我加载一个特定的url时,我会同时获得成功和错误吗?

这就是我在index.php中的内容:

<?php
require_once 'functions/lib.php';
require_once 'core/init.php';
// Ask for request URL that was submitted and define scriptPath. Explode content of REQUEST URL to evaluate validity.
$requestURL = (($_SERVER['REQUEST_URI'] != "") ? $_SERVER['REQUEST_URI'] : $_SERVER['REDIRECT_URL']);
$scriptPath = dirname($_SERVER['PHP_SELF']);
$requestURL = str_replace($scriptPath, "", $requestURL);
$requestParts = explode("/", $requestURL);
// Check for valid api version
$validAPIVersions = array("v1");
$apiVersion = $requestParts[1];
// If API Version not in valid API array return 404, else OK.
if (!in_array($apiVersion, $validAPIVersions)) {
    httpResponseCode(404);
    echo $GLOBALS['http_response_code'];
    echo "<br>" . "API Version not valid";
    exit();
}
// Check for valid API endpoint
$validEndPoints = array("tickets");
$endPoint = $requestParts[2];
if (!in_array($endPoint, $validEndPoints)) {
    httpResponseCode(404);
    echo $GLOBALS['http_response_code'];
    echo "<br>" . "Endpoint not valid";
    exit();
}
// get the endpoint class name
$endPoint = ucfirst(strtolower($endPoint));
$classFilePath = "$apiVersion/$endPoint.php";
if (!file_exists($classFilePath)) {
    httpResponseCode(404);
    echo $GLOBALS['http_response_code'];
    exit();
}
// load endpoint class and make an instance
try {
    require_once($classFilePath);
    $instance = new $endPoint($requestParts);
} catch (Exception $e) {
    httpResponseCode(500);
    echo $GLOBALS['http_response_code'];
    exit();
}

这就是相应的"Tickets.php"

<?php
echo "OK";
?>

在index.php的最后两行中,我正在加载特定的类(在URL中命名)。出于测试目的,我在这个文件中有一个"echo"OK。这是我加载所需URL时的结果:

http://api.medifaktor.de/v1/tickets

OK
Fatal error: Class 'Tickets' not found in /usr/www/users/kontug/api.medifaktor.de/webservice/index.php on line 45

我得到了我所期望的OK,但没有找到上课票的错误。第45行为

$instance = new $endPoint($requestParts);

有人能帮我一把吗?

最佳Sebastian

问题是没有定义类"Tickets"。加载tickets.php文件后,您正试图实例化一个类。加载文件与定义类不是一回事。在tickets.php(或其他包含的文件)中,您需要定义类,如下所示:

class Tickets
{
    // some properties here
    private $endpoint;
    // some methods here
    public function __construct($endpoint)
    {
        $this->endpoint = $endpoint;
    }
}

如果您不确定如何用PHP构建类,请阅读手册中关于类的部分。

更新:我在PHP5+版本的类中添加了一些示例代码。

在'ticket.php'文件中添加以下内容进行测试:

class Ticket {
    public function __construct()
    {
        echo 'testing';
    }
}

然后确保您是namespace还是require文件。