2014-12-04 84 views
0

我從API讀取一些數據,比我累了使用它,但有時部分數據丟失,即PHP - 對象數據捕獲錯誤缺少的屬性

$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); 

但它的繁瑣和醜陋的,是有一個較短/更清潔的方式?

回答

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(); 
+0

我可以做子類同樣的想法? – 2014-12-14 06:35:01

+0

你是什麼意思? – mleko 2014-12-14 07:47:18

+0

我的意思是'對象繼承',即從丟失屬性時拋出異常的對象繼承 – 2014-12-15 08:30:50