[英]Read data from protected object in PHP
我在PHP中有這段代碼(它只是從API檢索一些傳遞方法,API是第三方)
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 } ?>
但是我得到一個錯誤:
致命錯誤:未捕獲錯誤:無法訪問/data/web/virtuals/175241/virtual/www/doprava.php:39中的$ data在/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的內容
我同意您的意見,文檔對此不太清楚。 如果您查看源代碼 ,可以看到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()
// ...
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.