How to Dynamically Invoke a Class Method in PHP?

Overview of some common techniques in PHP to dynamically invoke class methods

In this article we look at some ways to invoke PHP class methods dynamically. The intention is not to rewrite the PHP manual but to highlight some common techniques.

Using a Variable

Dynamic Class Method Invocation:

// PHP 5.3.0+
$classInstance = new ClassName();
$classInstance->{$methodName}($arg1, $arg2, $arg3);
$classInstance->$methodName($arg1, $arg2, $arg3);

Static Class Dynamic Method Invocation:

$className = 'ClassName';
$methodName = 'methodName';
$className::$methodName(); // PHP 5.3.0+

Advanced Callables

Dynamic Class Method Invocation:

$func = [new ClassName(), $methodName];
$func(); // PHP 5.4.0+

Static Class Dynamic Method Invocation:

$func = ['ClassName', $methodName];
$func(); // PHP 5.4.0+

$func = 'ClassName::methodName';
$func(); // PHP 7.0.0+; prior, it raised a fatal error

Using call_user_func() and call_user_func_array()

call_user_func():

Calls the callback given by the first parameter and passes the remaining parameters as arguments.

// PHP 5.3.0+
$classInstance = new ClassName();
call_user_func_array([$classInstance, $methodName], $arg1, $arg2, $arg3);

// using namespace
call_user_func(__NAMESPACE__ . '\ClassName::methodName', $arg1, $arg2, $arg3);
call_user_func([__NAMESPACE__ . '\ClassName', 'methodName'], $arg1, $arg2, $arg3);

call_user_func_array():

Calls the callback given by the first parameter and passes arguments that are supplied as an array given by the second parameter.

// PHP 5.3.0+
$classInstance = new ClassName();
call_user_func_array([$classInstance, $methodName], [$arg1, $arg2, $arg3]);

// using namespace
call_user_func_array(__NAMESPACE__ . '\ClassName::methodName', [$arg1, $arg2, $arg3]);
call_user_func_array([__NAMESPACE__ . '\ClassName', 'methodName'], [$arg1, $arg2, $arg3]);

Which Method Is Faster?

From all the ways listed, using a variable for class method invocation or directly invoking methods on a class instance is the fastest. Using call_user_func() and call_user_func_array() would be comparatively slower than all other methods because it involves a function call.


Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.