Summary: in this tutorial, you’ll learn about the call_user_func_array()
function and how to use it to call a function dynamically.
Introduction to the PHP call_user_func_array() function
The call_user_func_array()
function calls a callback function with parameters. Here’s the syntax of the call_user_func_array()
function:
call_user_func_array(callable $callback, array $args): mixed
Code language: PHP (php)
The call_user_func_array()
has two parameters:
$callback
is the name of a function or any callable that will be called.$args
is an array that contains parameters of the$callback
.
The call_user_func_array()
returns the value of the $callback
.
PHP call_user_func_array function example
The following example illustrates how to use the call_user_func_array()
function:
<?php
function add(int $a, int $b): int {
return $a + $b;
}
$result = call_user_func_array('add',[10,20]);
echo $result; // 30
Code language: PHP (php)
How it works.
- First, define a function
add()
that returns the sum of two integers. - Second, call the
add()
function via thecall_user_func_array()
function. The first argument is the function name, and the second argument is an array of arguments of theadd()
function. - Third, show the result to the output.
Summary
- Use the PHP
call_user_func_array()
function to call a callback with parameters
Did you find this tutorial useful?