Friday, 13 July 2018

How To Dynamically Invoke A Class Method In PHP?

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 = array(new ClassName, $methodName);
$func(); // PHP 5.4.0+

Static Class Dynamic Method Invocation:

$func = array("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(array($classInstance, $methodName), $arg1, $arg2, $arg3);

// using namespace
call_user_func(__NAMESPACE__ . '\ClassName::methodName', $arg1, $arg2, $arg3);
call_user_func(array(__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(array($classInstance, $methodName), array($arg1, $arg2, $arg3));

// using namespace
call_user_func_array(__NAMESPACE__ . '\ClassName::methodName', array($arg1, $arg2, $arg3));
call_user_func_array(array(__NAMESPACE__ . '\ClassName', 'methodName'), array($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.

0 comments:

Post a Comment