gpt4 book ai didi

php - fatal error : Cannot use object of type as array

转载 作者:行者123 更新时间:2023-12-02 17:35:13 26 4
gpt4 key购买 nike

所以,当我尝试从对象单例获取数组列表时出现此错误。

这是 CardType.php 上的单例

class CardTypeAPIAccessor extends GuzzleClient
{

private $client;

public function __construct($client)
{
if($client instanceof GuzzleClient)
{
$this->client = $client;
}
else
{
$this->client = parent::getClient();
}
}

public function getCardTypes() {
$cardTypes = array();

try
{

$response = $this->client->get('admin/card/type',
['headers' => ['Authorization' => $_SESSION['login']['apiKey']]
]);

$statusCode = $response->getStatusCode();
// Check that the request is successful.
if ($statusCode == 200)
{
$error = $response->json();
foreach ($error['types'] as $type)
{
$cardType = new CardType();
$cardType->setCardTypeId($type['card_type_id']);
$cardType->setCategory($type['category']);

array_push($cardTypes, $cardType);
}
}
}
catch(RequestException $e)
{
//todo
echo $e->getRequest() . "</br>";
if ($e->hasResponse())
{
echo $e->getResponse() . "</br>";
}
}
return $cardTypes;
}
}

这是card_type.php 上的代码

<?php
$cardTypes = $cardTypeAPIAccessor->getCardTypes();
foreach ($cardTypes as $cardType){
$Type = new CardType();
?>
<tr>
<!-- The error is here-->
<td class="numeric"><?php echo $Type->getCardTypeId($cardType['card_type_id']); ?></td>
<td class="numeric"><?php echo $Type->getCategory($cardType['category']); ?></td>
</tr>

错误提示:无法将 CardType 类型的对象用作数组

我的代码有问题吗?

谢谢

最佳答案

看起来您已经获得了此行所需的所有值:

$cardTypes = $cardTypeAPIAccessor->getCardTypes();

所以在我看来,在你的循环中,你只需要:

foreach ($cardTypes as $cardType){
?>
<tr>
<td class="numeric"><?php echo $cardType->getCardTypeId(); ?></td>
<td class="numeric"><?php echo $cardType->getCategory(); ?></td>
</tr>

尽管这实际上只是基于给定代码和缺少的 CardType 类的猜测。但我认为不需要在循环内生成新对象。

关于php - fatal error : Cannot use object of type as array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27451706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com