我从API中读取了一些数据,而不是我厌倦了使用它,但有时缺少部分数据,即
$api_response->Items->Item->ItemAttributes->ItemDimension
如果缺少任何属性,它将生成php错误,我正在寻找一种方法来捕获此错误作为例外。
我可以写下面的代码:
if (!property_exists($this->api_response->Items,"Item") )
throw new Exception("Can't use AM API", 1);
if (!property_exists($this->api_response->Items->Item,"ItemAttributes") )
throw new Exception("Can't use AM API", 1);
但它既乏味又丑陋,是否有更短/更清洁的方式?
答案 0 :(得分:1)
您可以使用某种代理来简化此
<?php
class PropertyProxy{
private $value;
public function __construct($value){
$this->value = $value;
}
public function __get($name){
if(!property_exists($this->value, $name)){
throw new Exception("Property: $name is not available");
}
return new self($this->value->{$name});
}
public function getValue(){
return $this->value;
}
}
$proxiedResponse = new PropertyProxy($api_response);
$proxiedResponse->Items->Item->ItemAttributes->ItemDimension->getValue();