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. Commented 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());
Sign up to request clarification or add additional context in comments.

1 Comment

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
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.