2014-10-16 41 views
-1

這是否總是安全或在某些情況下會導致錯誤?安全地訪問php中的對象的屬性

if(isset($myVar) && $myVar->myProp !== 'error') { 
    ... 
+0

如果它不存在,這可能會導致錯誤.. 。但是,當然,你在使用它之前檢查它是否存在,對吧? – 2014-10-16 13:08:38

+0

好的,試着讓它更清晰 – Cotten 2014-10-16 13:17:01

+0

對我來說,在編輯之前是同樣的問題。 – 2014-10-16 13:20:20

回答

0

是的,如果該屬性不存在,會引發錯誤。檢查它存在與property_exists

$myVar = new myVar(); 
if((isset($myVar) && property_exists('myVar', 'myProp')) 
    && $myVar->myProp !== 'error') { 

} 
1

這似乎是在飛行中定義屬性的情況。雖然這是可能的(合法的)使用property_exists(),這將是更好的實際執行的財產在類定義的所有腦幹:

Class someExample { 
    public $myProp = false; // now it will ALWAYS exist for any instance of someExample 
}