![](/img/trans.png)
[英]Fatal error: Uncaught Error: Cannot use object of type Entrada as array
[英]Fatal Error : Cannot use object of type as array
因此,当我尝试从对象单例中获取数组列表时,出现了此错误。
这是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
类的猜测。 但我认为不需要在循环内生成新对象。
$cardType
变量是CardType类的实例,而不是数组。 问题是,当它是一个对象时,您就像在使用数组一样使用它。 所以这
$cardType['card_type_id']
应该
$cardType->getCardTypeID()
有时您的响应会变成基于对象的,无法轻易访问。 用例,例如从控制器或任何第三方API中的其他控制器获取数据时。
这样就可以用这种方式获取数据
$object->getData(1); // here 1 is for associated data form.
在我的用例中,当我尝试从其他控制器访问数据时,我面临着相同的问题。
$attendanceController = new AttendanceController();
$offDayData = $attendanceController->getAttendanceOffDays($req);
return $offDayData->getData(1)['response'];
当您尝试从Controller类获取数据时,响应将以另一种方式包装。 因此您必须使用getData(1)方法访问该响应。 在我的解决方案中,我使用了。 它会在所有情况下都起作用,然后您要从不同的ControllerCalss获取数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.