In PHP, the call_user_method() function allows you to dynamically invoke a method on an object. Typically, we call a method directly through an object like this:
$obj->method();
However, in certain cases, you may want to call an object's method dynamically based on a variable, which can be done using call_user_method().
call_user_method ( string $method_name , object $obj , mixed $parameter [, mixed $... ] ) : mixed
Parameter explanation:
class MyClass {
public function myMethod($arg1, $arg2) {
echo "arg1=$arg1, arg2=$arg2";
}
}
$obj = new MyClass();
call_user_method('myMethod', $obj, 'value1', 'value2'); // arg1=value1, arg2=value2
In the example above, we define the MyClass class with the myMethod() method. We then create an instance and dynamically call myMethod() using call_user_method(), passing two parameters and outputting the result.
class MyClass {
public function myMethod($arg1, $arg2) {
echo "arg1=$arg1, arg2=$arg2";
}
}
$obj = new MyClass();
call_user_func([$obj, 'myMethod'], 'value1', 'value2'); // arg1=value1, arg2=value2
This example uses call_user_func() with an array containing the object and method name. It works similarly to call_user_method() and is compatible with PHP 7 and newer versions.
This article explained the usage of the call_user_method() function in PHP and its role in dynamic method invocation. Since this function was deprecated in PHP 7, developers are advised to use modern alternatives like call_user_func() to ensure compatibility and maintainability of their code.