致命错误:不能将类型的对象用作数组


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>

错误说:不能使用卡类型类型的对象作为数组

我的代码出错了吗?

谢谢

看起来您已经通过以下行获得了所有必要的值:

$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'];

当您尝试从控制器类获取数据时,响应将以不同的方式包装。 因此,您必须使用 getData(1) 方法来访问该响应。在我的解决方案中,我使用了它。它将在所有情况下工作,然后您希望从不同的控制器卡斯