PHP获取静态方法


PHP get static methods

我想通过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手册中读到如何获取类的函数成员(get_class_methods)。但是我总是得到没有信息的每个成员,不管它是否是静态的。

如何确定方法的上下文?

谢谢你的帮助

使用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());

我知道的一种方法是使用反射。特别是,可以这样使用ReflectionClass::getMethods:

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

这样做的困难在于您需要启用反射,而这不是默认情况。