2011-11-28 61 views
5

我想通過VAR(像這樣)調用類方法:PHP獲得靜態方法

$var = "read"; 
$params = array(...); //some parameter 
if(/* MyClass has the static method $var */) 
{ 
    echo MyClass::$var($params); 
} 
elseif (/* MyClass hat a non-static method $var */) 
{ 
    $cl = new MyClass($params); 
    echo $cl->$var(); 
} 
else throw new Exception(); 

我在閱讀的PHP手冊如何獲取類(get_class_methods)的函數成員。但如果它的靜態或不靜態,我總是得到每一個沒有信息的成員。

我如何確定方法的上下文?

感謝你的幫助

+1

另請注意,PHP中支持從實例變量調用靜態方法。 – JRL

回答

13

使用類ReflectionClass

On Codepad.org: http://codepad.org/VEi5erFw 
<?php 

class MyClass 
{ 
    public function func1(){} 
    public static function func2(){} 
} 

$reflection = new ReflectionClass('MyClass'); 
var_dump($reflection->getMethods(ReflectionMethod::IS_STATIC)); 

這將輸出所有靜態功能。

或者,如果你想確定給定函數是否是靜態的,你可以使用ReflectionMethod類:

在Codepad.org:我知道http://codepad.org/2YXE7NJb

<?php 

class MyClass 
{ 
    public function func1(){} 
    public static function func2(){} 
} 

$reflection = new ReflectionClass('MyClass'); 

$func1 = $reflection->getMethod('func1'); 
$func2 = $reflection->getMethod('func2'); 

var_dump($func1->isStatic()); 
var_dump($func2->isStatic()); 
+0

這基本上是我要說的,你可以使用$ func1的hasMethod來確定是否拋出異常 –

+0

正是我所需要的,謝謝 – 0xDEADBEEF

4

一種方法是使用Reflection。特別是,一個會用ReflectionClass::getMethods這樣:

$class = new ReflectionClass("MyClass"); 
$staticmethods = $class->getMethods(ReflectionMethod::IS_STATIC); 
print_r($staticmethods); 

這樣做的困難在於你必須激活反思,它是不是默認。