PHP – call a function with arguments in array examples

PHP call_user_func_array() can be used to call a function with arguments in an array. This gives us the flexibility to pass variable number of arguments. Here is code snippet for it.

call_user_func_array() on a function

<?php
function f1($arg1, $arg2) {
  print "arg1=$arg1\n";
  print "arg1=$arg2\n";
}
$a = array("v1", "v2");
call_user_func_array('f1', $a);
?>
arg1=v1
arg1=v2
Env: PHP 5.5.9 (Linux)

call_user_func_array() on class static method

<?php
class Foo {
  static function f1($arg1, $arg2) {
    print "arg1=$arg1\n";
    print "arg1=$arg2\n";
  }
}
$a = array("v1", "v2");
call_user_func_array('Foo::f1', $a);
?>
arg1=v1
arg1=v2
Env: PHP 5.5.9 (Linux)

call_user_func_array() on object method

<?php
class Foo {
  function f1($arg1, $arg2) {
    print "arg1=$arg1\n";
    print "arg1=$arg2\n";
  }
}
$obj = new Foo();
$a = array("v1", "v2");
call_user_func_array(array($obj, 'f1'), $a);
?>
arg1=v1
arg1=v2
Env: PHP 5.5.9 (Linux)
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments