2017-10-20 86 views
0

有沒有辦法檢查我已經設置了一個ReflectionProperty來訪問?如何檢查ReflectionProperty是否可訪問?

class Foo { 
    private $baz = 'bar'; 
} 

$foo = new Foo(); 

$prop = new ReflectionProperty($foo, 'baz'); 
$prop->setAccessible(true); 

$prop->isPrivate();會前和設置的易用性(預期)後返回true。有沒有辦法告訴我已經將可訪問性設置爲true?

documentation在ReflectionProperty類中沒有顯示任何類似$accessible的屬性,所以我不確定它如何使它可訪問,除非它在Foo類中完成。

回答

0

您可以用下面的方法try-catch塊內:

ReflectionProperty::getValue 

拋出一個ReflectionException如果該屬性是不可訪問。您可以使用 ReflectionProperty :: setAccessible()將 設置爲受保護或私有屬性。

文檔鏈接:
http://php.net/manual/en/reflectionproperty.getvalue.php

代碼:

function isPropertyAccessible($property){ 
    $result = true; 
    try{ 
     ReflectionProperty::getValue($property); 
    } 
    catch(ReflectionException $e){ 
     $result = false; 
    } 
     return $result; 
    } 
+0

我意識到這可能弄清楚。我想我想知道是否有更清晰的檢查方式。對我來說,他們會允許我們設置可訪問性,但不檢查它,但如果我們不這樣做,則會拋出異常。 – GreeKatrina

+0

@GreeKatrina我想知道爲什麼你需要檢查無障礙。看起來你正在做一些有趣的項目。我可以知道它的一些開源項目嗎?你能否請我的答案upvote。 – Tarun

相關問題