从 PHP 中的受保护对象读取数据

Read data from protected object in PHP

我在 PHP 中有这段代码(它只是从 API 中检索了一些交付方法,API 是第 3 方)

use MPAPI\Services\DeliveryMethods;
use MPAPI\Services\Deliveries;
use MPAPI\Entity\PartnerDelivery;
use MPAPI\Entity\GeneralDelivery;
$deliveryMethods = new DeliveryMethods($mpapiClient);
$response = $deliveryMethods->get();
var_dump($response);

响应是:

array(2) {
  [0]=>
  object(MPAPI\Entity\DeliveryMethod)#35 (1) {
    ["data":protected]=>
    array(7) {
      ["id"]=>
      string(4) "Test"
      ["title"]=>
      string(18) "Testovacia doprava"
      ["price"]=>
      int(10)
      ["cod_price"]=>
      int(10)
      ["free_limit"]=>
      int(0)
      ["delivery_delay"]=>
      int(5)
      ["is_pickup_point"]=>
      bool(false)
    }
  }
  [1]=>
  object(MPAPI\Entity\DeliveryMethod)#36 (1) {
    ["data":protected]=>
    array(7) {
      ["id"]=>
      string(3) "UPS"
      ["title"]=>
      string(22) "Kuriérska služba UPS"
      ["price"]=>
      int(5)
      ["cod_price"]=>
      int(0)
      ["free_limit"]=>
      int(0)
      ["delivery_delay"]=>
      int(4)
      ["is_pickup_point"]=>
      bool(false)
    }
  }
}

我想在 PHP 中访问它,所以我的 foreach 循环看起来像:

<?php foreach ($response[0]->data as $item) { ?>
// ...
<?php } ?>

但是我得到一个错误:

Fatal error: Uncaught Error: Cannot access protected property MPAPI\Entity\DeliveryMethod::$data in /data/web/virtuals/175241/virtual/www/doprava.php:39 Stack trace: #0 {main} thrown in /data/web/virtuals/175241/virtual/www/doprava.php on line 39

那么如何正确读取PHP中的这个数据呢?

如果我像这样更改 foreach 循环:

<?php foreach ($response as $item) { ?>
// ...
<?php } ?>

我会得到另一个错误:

Fatal error: Uncaught Error: Cannot use object of type MPAPI\Entity\DeliveryMethod as array

在 API 的文档中没有任何内容 https://github.com/mallgroup/mpapi-client-php/blob/master/doc/DELIVERIES.md

我同意你的看法,文档对此不太清楚。 如果你查看 the source,你可以看到 class MPAPI\Entity\DeliveryMethod 有这个方法 returns 数据作为数组:

/**
 * @see \MPAPI\Entity\AbstractEntity::getData()
 */
public function getData()
{
    return [
        self::KEY_ID => $this->getId(),
        self::KEY_TITLE => $this->getTitle(),
        self::KEY_PRICE => $this->getPrice(),
        self::KEY_COD_PRICE => $this->getCodPrice(),
        self::KEY_FREE_LIMIT => $this->getFreeLimit(),
        self::KEY_DELIVERY_DELAY => $this->getDeliveryDelay(),
        self::KEY_PICKUP_POINT => $this->isPickupPoint()
    ];
}

所以,你会做这样的事情

<?php 
$methodList = $deliveryMethods->get();
foreach ($methodList as $method) { 
    $methodData = $method->getData();
    // OR
    $methodTitle = $method->getTitle()
    // ...
} 
?>