PHP get static methods

亡梦爱人 提交于 2020-01-02 03:37:09

问题


i want to call a class method by a var (like this):

$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();

i read in the php-manual how to get the function-members of a class (get_class_methods). but i get always every member without information if its static or not.

how can i determine a method´s context?

thank you for your help


回答1:


Use the class 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) );

This will output all static functions.

Or if you want to determine whether a given function is static you can use the ReflectionMethod class:

On 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());



回答2:


One way I know of is to use Reflection. In particular, one would use ReflectionClass::getMethods as such:

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

The difficulty of this is that you need to have Reflection enabled, which it is not by default.



来源:https://stackoverflow.com/questions/8299886/php-get-static-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!