How can I call a static method from a class if all I have is a string of the class name?

Depending on version of PHP:

call_user_func(array($class_name, 'doSomething'));
call_user_func($class_name .'::doSomething'); // >5.2.3

To unleash the power of IDE autocomplete and error detection, use this:

$class_name = 'ClassPeer';

$r = new \ReflectionClass($class_name );

// @param ClassPeer $instance

$instance =  $r->newInstanceWithoutConstructor();

//$class_name->doSomething();
$instance->doSomething();

Basically here we are calling the static method on an instance of the class.


Use call_user_func. Also read up on PHP callbacks.

call_user_func(array($class_name, 'doSomething'), $arguments);

Tags:

Php