2016-09-30 66 views
1
$a = (object)['foo' => 'bar']; 
$a->baz; 

$a->baz調用返回NULL而且還提出了一個通知Undefined property..未定義的屬性。當屬性不存在時,獲得null對我來說沒什麼問題,但是有什麼辦法可以抑制這個特定的通知(來自配置或某些事情,而不是if語句或@符號,這很明顯),但繼續看到其他通知?避免通知:在stdClass的

回答

1

一個可能的解決方案是創建它是使用__get魔術方法定製性病類:

class customStdClass 
{ 
    public function __get($name) 
    { 
     if (!isset($this->$name)) { 
      return null; 
     } 

     return $this->$name; 
    } 

    public static function fromArray($attributes) 
    { 
     $object = new self(); 

     foreach ($attributes as $name => $value) { 
      $object->$name = $value; 
     } 

     return $object; 
    } 
} 

你可以用它喜歡:

$object = customStdClass::fromArray(['foo' => 'bar']); 
echo $object->foo; 
echo $object->baz; // no warning here 
+1

是的,這就是我目前完成和我試圖避免。 –