11

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
  • 1
    Note also that calling a static method from an instance variable is supported in PHP.
    – JRL
    Dec 11, 2011 at 21:29

2 Answers 2

29

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());
1
  • This is basically what I was going to say as well, you can use hasMethod of $func1 to determine whether or not to throw and exception Nov 28, 2011 at 17:50
9

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.