【问题标题】:Read data from protected object in PHP从 PHP 中的受保护对象中读取数据
【发布时间】:2018-07-19 02:55:34
【问题描述】:

我在 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 } ?>

但我得到一个错误:

致命错误:未捕获的错误:无法访问受保护的属性 MPAPI\Entity\DeliveryMethod::$data in /data/web/virtuals/175241/virtual/www/doprava.php:39 堆栈跟踪:#0 {main} 在 /data/web/virtuals/175241/virtual/www/doprava.php 上抛出 第 39 行

那么如何在 PHP 中正确读取这些数据呢?

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

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

我会得到另一个错误:

致命错误:未捕获错误:无法使用对象类型 MPAPI\Entity\DeliveryMethod 作为数组

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

【问题讨论】:

标签: php object protected


【解决方案1】:

我同意你的观点,文档对此并不太清楚。 如果您查看the source,您可以看到MPAPI\Entity\DeliveryMethod 类具有将数据作为数组返回的方法:

/**
 * @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()
    // ...
} 
?>

【讨论】:

  • 是的,我知道它会返回一个数组,我将它转储了(这是我的问题),但每次我遇到错误时,我都不知道如何正确访问这些值。我想做“foreach ($response as $item)”,但它会引发错误。
猜你喜欢
  • 1970-01-01
  • 2018-03-12
  • 2019-05-21
  • 2013-11-12
  • 2014-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-18
相关资源
最近更新 更多