对象数据捕获错误缺少属性


object data catch error missing attributes

我从 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);

但它既乏味又丑陋,有没有更短/更干净的方法?

您可以使用某种代理来简化此操作

<?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();