php-对象数据捕获错误缺少属性
我从一个API中读取了一些数据,然后我开始尝试使用它,但有时部分数据丢失了,例如php-对象数据捕获错误缺少属性,php,Php,我从一个API中读取了一些数据,然后我开始尝试使用它,但有时部分数据丢失了,例如 $api_response->Items->Item->ItemAttributes->ItemDimension 如果任何属性丢失,它将生成一个php错误,我正在寻找一种方法将此错误作为异常捕获 我可以编写以下代码: if (!property_exists($this->api_response->Items,"Item") ) throw new Excepti
$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);
但是它既单调又丑陋,有没有更简洁的方法?您可以使用某种代理来简化此过程
<?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();
我可以对子分类做同样的想法吗?我的意思是“对象继承”,即从一个对象继承,如果属性丢失,该对象会抛出异常