2011-03-24 85 views
4

有了這個代碼,我想測試,如果我能現在卻調用某些功能找出一個方法是否受到保護公衆

if (method_exists($this, $method)) 
    $this->$method(); 

我希望能夠限制執行如果$方法受保護,我需要做什麼?

回答

7

你會想要使用Reflection

class Foo { 
    public function bar() { } 
    protected function baz() { } 
    private function qux() { } 
} 
$f = new Foo(); 
$f_reflect = new ReflectionObject($f); 
foreach($f_reflect->getMethods() as $method) { 
    echo $method->name, ": "; 
    if($method->isPublic()) echo "Public\n"; 
    if($method->isProtected()) echo "Protected\n"; 
    if($method->isPrivate()) echo "Private\n"; 
} 

輸出:

bar: Public 
baz: Protected 
qux: Private 

您還可以通過類和函數的名稱進行實例化的ReflectionMethod對象:

$bar_reflect = new ReflectionMethod('Foo', 'bar'); 
echo $bar_reflect->isPublic(); // 1 
+0

我需要測試$方法是否存在,或會是公衆如果該方法未定義,則爲0? – Moak 2011-03-24 06:34:27

+0

如果您嘗試在不存在的方法上構建ReflectionMethod,它將引發異常。他使用ReflectionObject執行的第一件事是迭代通過現有的方法,所以這不是問題 – 2011-03-24 06:44:24

+0

@Moak:你可以使用['ReflectionObject :: hasMethod'](http://us2.php.net/manual/en/reflectionclass .hasmethod.php)來測試方法的存在。這可以在課堂外進行檢查時使用私人方法。 – Charles 2011-03-24 06:56:38

0

您應該使用ReflectionMethod。您可以使用isProtectedisPublic以及getModifiers

http://www.php.net/manual/en/class.reflectionmethod.php http://www.php.net/manual/en/reflectionmethod.getmodifiers.php

$rm = new ReflectionMethod($this, $method); //first argument can be string name of class or an instance of it. i had get_class here before but its unnecessary 
$isPublic = $rm->isPublic(); 
$isProtected = $rm->isProtected(); 
$modifierInt = $rm->getModifiers(); 
$isPublic2 = $modifierInt & 256; $isProtected2 = $modifierInt & 512; 

至於檢測是否該方法存在,您可以像現在使用method_exists那樣執行此操作,或者只是嘗試構建ReflectionMethod,並且如果它不存在,則會拋出異常。 ReflectionClass有一個函數getMethods可以爲你提供一個類的所有方法的數組,如果你想使用它的話。

免責聲明 - 我不知道PHP反射太清楚,有可能是一個更直接的方式與ReflectionClass做到這一點還是其他什麼東西