The call_user_func_array Function

The call_user_func_array function allows you to call a callback by passing parameters as an array. The first parameter is the name of the function or method, and the second is an array of arguments.

Syntax

phpcall_user_func_array(callable $callback, array $args);

Example

Calling a simple function by passing parameters through an array:

php<?php
  function sum($a, $b) {
    return $a + $b;
  }
  
  $res = call_user_func_array('sum', [2, 3]);
  echo $res;
?>

Code execution result:

php5

Example

Calling a class method by passing parameters:

php<?php
  class Calculator {
    public function multiply($a, $b) {
      return $a * $b;
    }
  }
  
  $calc = new Calculator();
  $res = call_user_func_array([$calc, 'multiply'], [4, 5]);
  echo $res;
?>

Code execution result:

php20

Example

Usage with an anonymous function:

php<?php
  $func = function($a, $b, $c) {
    return $a + $b + $c;
  };
  
  $res = call_user_func_array($func, [1, 2, 3]);
  echo $res;
?>

Code execution result:

php6

See Also

  • the call_user_func function,
    which calls a callback function with individual arguments
  • the function_exists function,
    which checks for the existence of a function