【发布时间】:2014-12-12 20:35:10
【问题描述】:
所以,当我尝试从对象单例中获取数组列表时出现了这个错误。
这个是 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 类型的对象作为数组
我的代码出错了吗?
谢谢
【问题讨论】:
-
第几行?你能加粗吗?
-
在此代码上
<td class="numeric"><?php echo $Type->getCardTypeId($cardType['card_type_id']); ?></td> <td class="numeric"><?php echo $Type->getCategory($cardType['category']); ?></td> -
基本上将
$cardType['card_type_id']更改为$cardType->card_type_id应该可以解决问题。如果要调试,只需在错误行之前使用var_dump($cardType); die();。