382 of 410 menu

The call_user_func Function

The call_user_func function allows you to call any callable function by passing arguments to it. The first parameter accepts the function name or an anonymous function, and the subsequent parameters accept arguments for the function being called.

Syntax

call_user_func(callable $callback, mixed ...$args): mixed

Example

Let's call the standard function strtoupper for the string 'hello':

<?php $res = call_user_func('strtoupper', 'hello'); echo $res; ?>

Code execution result:

'HELLO'

Example

Let's call a user-defined function with several arguments:

<?php function sum($a, $b) { return $a + $b; } $res = call_user_func('sum', 5, 3); echo $res; ?>

Code execution result:

8

Example

Using an anonymous function as a callback:

<?php $res = call_user_func(function($name) { return "Hello, $name!"; }, 'John'); echo $res; ?>

Code execution result:

'Hello, John!'

See Also

byenru