PHP get static methods

0xDEADBEEF picture 0xDEADBEEF · Nov 28, 2011 · Viewed 10k times · Source

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

Answer

ComFreek picture ComFreek · Nov 28, 2011

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