[英]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.