我想通过var(像这样)来调用类方法:
$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-manual中读到了如何获取类的函数成员(get_class_methods)。但是如果它是静态的,我总是得到每个没有信息的成员。
我如何确定方法的上下文?
谢谢你的帮助
答案 0 :(得分: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());
答案 1 :(得分:4)
我知道的一种方法是使用Reflection。特别是,人们会使用ReflectionClass::getMethods
:
$class = new ReflectionClass("MyClass");
$staticmethods = $class->getMethods(ReflectionMethod::IS_STATIC);
print_r($staticmethods);
这样做的难点在于您需要启用反射,默认情况下不是这样。