You have multiple options to do this
- using a string variable for the class name and the method name
- using callbacks together with call_user_func()
- using Reflection
The following examples shall demonstrate these options:
<?php
namespace vendor\foo;
class Bar {
public static function foo($arg) {
return 'foo ' . $arg;
}
}
Option 1 : Using a string variable for the classname and the method name:
/* prepare class name and method name as string */
$class = '\vendor\foo\Bar';
$method = 'foo';
// call the method
echo $class::$method('test'), PHP_EOL;
// output : foo test
Option 2 : Perpare a callback variable and pass it to call_user_func()
:
/* use a callback to call the method */
$method = array (
'\vendor\foo\Bar', // using a classname (string) will tell call_user_func()
// to call the method statically
'foo'
);
// call the method with call_user_func()
echo call_user_func($method, 'test'), PHP_EOL;
// output : foo test
Option 3 : Use ReflectionMethod::invoke() :
/* using reflection to call the method */
$method = new \ReflectionMethod('\vendor\foo\Bar', 'foo');
// Note `NULL` as the first param to `ReflectionMethod::invoke` for a static call.
echo $method->invoke(NULL, 'test'), PHP_EOL;
// output : foo test