PHP call_user_func: Usage Guide

In PHP, the call_user_func function can be used to invoke a specific function or method. The syntax for using the call_user_func function is as follows:

call_user_func(callable $callback [, $parameter [, ...]])

The $callback parameter is a callable callback function, which can be a string representing a function name, an array (with the first element being an object or class name, and the second element being a method name), or an anonymous function. The $parameter parameter specifies the arguments passed to the callback function.

Here are some examples of using the call_user_func function:

  1. Invoke a function:
function greet($name) {
    echo "Hello, $name!";
}

call_user_func('greet', 'John');
  1. Invoke a method of an object:
class Greeting {
    public function sayHello($name) {
        echo "Hello, $name!";
    }
}

$greeting = new Greeting();
call_user_func([$greeting, 'sayHello'], 'John');
  1. Invoke an anonymous function.
$greet = function($name) {
    echo "Hello, $name!";
};

call_user_func($greet, 'John');

It’s important to note that the call_user_func function has been deprecated in PHP version 7.0.0. It is recommended to use the $callback(…$parameters) syntax to call callback functions instead.

bannerAds