因此,我有一个任务访问外部api,然后将结果呈现给一个单独的FE。我做了一个ApiClass和一个ProductListClass。然后从索引页中包含两个类文件,然后尝试调用ProductListClass方法,但是我得到了一个ApiClass未找到的错误,并且无法完全计算出原因,任何帮助都非常感谢。
这是我的ApiClass
<?php
namespace app\ApiClass;
use GuzzleHttp\Client;
class ApiClass
{
protected $url;
protected $client;
public function __construct(Client $client)
{
$this->url = 'http://external-api';
$this->client = new $client; //GuzzleHttp\Client
}
private function getResponse(string $uri = null)
{
$full_path = $this->url;
$full_path .=$uri;
$result = $this->client->get($full_path);
return json_decode($result->getBody()->getContents(), true);
}
public function getData($uri)
{
return $this->getResponse($uri);
}
}这是我的ProductListClass
<?php
include ("ApiClass.php");
class ProductList
{
private $apiClass;
public function __construct(ApiClass $apiClass) {
$this->apiClass = $apiClass;
}
public function getList() {
$urlAppend = 'list';
$list = $this->api->getData($urlAppend);
if(array_key_exists("error", $list)) {
$this->getList();
} else {
return $list;
}
}
}这是索引页
<?php
include_once 'app/ProductListClass.php';
include_once 'app/ApiClass.php';
$api = new ApiClass();
$productList = new ProductList($api);
$productList->getList();这就是我所犯的错误
致命错误:未捕获错误:在/Applications/XAMPP/xamppfiles/htdocs/test/index.php:6堆栈跟踪中找不到类“ApiClass”:#0 {main}抛出在第6行的/Applications/XAMPP/xamppfiles/htdocs/test/index.php中
发布于 2019-11-01 17:50:28
您需要从正确的命名空间实例化ApiClass,而ApiClass的完全限定名(FQN)是app\ApiClass\ApiClass。你要么打电话
$api = app\ApiClass\ApiClass();或仅通过导入文件头中的命名空间来使用类名:
use app\ApiClass\ApiClass;
include_once 'app/ProductListClass.php';
include_once 'app/ApiClass.php';
$api = new ApiClass();
...每个文件都声明名称空间,因此不能通过在不同上下文中包含文件来更改它们。文件中没有定义任何名称空间,这意味着它是全局命名空间(如您的ProductListClass)。
GuzzleHttp\Client
如果要将Client实例传递给ApiClass,则需要实例化它,无需再次在其上使用new。如果您将FQN字符串作为参数,您可能会这样做,但这不是一个好的实践(除非在某些依赖项注入库中执行这种魔术)。
因此,要么这样做(首选):
class ApiClass
{
...
public function __construct(Client $client)
{
$this->url = 'http://external-api';
$this->client = $client;
}使用api实例化:
$api = new ApiClient(new GuzzleHttp\Client());或者在没有参数的构造函数中实例化:
public function __construct()
{
$this->url = 'http://external-api';
$this->client = new GuzzleHttp\Client();
}Ps。我认为您应该学会使用作曲家及其自动包含类文件(自动包含类文件)--使用库(和您自己的类)会容易得多。
https://stackoverflow.com/questions/58663562
复制相似问题