How can I dynamically invoke a class method in PHP? The class method is not static. It appears that
call_user_func(...)
only works with st
As of PHP7, you use an array-like way:
// Static call only
[TestClass::class, $methodName](...$args);
// Dynamic call, static or non-static doesn't matter
$instance = new TestClass;
[$instance, $methodName](...$args);
Just replace the class name with TestClass
, the method name with $methodName
and the method arguments with ...$args
. Note that, in the later case, it doesn't matter that the method is static or non-static; PHP will call it automatically.