call_user_func() or call_user_func_array() functions in PHP

By: Boards Viewed: 153307 times  Printer Friendly Format    


If you want to call a static function (PHP5) in a variable method:
Make an array of two entries where the 0th entry is the name of the class to be invoked ('self' and 'parent' work as well) and the 1st entry is the name of the function.  Basically, a 'callback' variable is either a string (the name of the function) or an array (0 => 'className', 1 => 'functionName').


Then, to call that function, you can use either call_user_func() or call_user_func_array().  Examples:


<?php
class A {
  protected $a;
  protected $c;
  function __construct() {
$this->a = array('self', 'a');
$this->c = array('self', 'c');
  }
  static function a($name, &$value) {
    echo $name,' => ',$value++,"\n";
  }
  function b($name, &$value) {
call_user_func_array($this->a, array($name, &$value));
  }
  static function c($str) {
    echo $str,"\n";
  }
  function d() {
call_user_func_array($this->c, func_get_args());
  }
  function e() {
call_user_func($this->c, func_get_arg(0));
  }
}
class B extends A {
  function __construct() {
$this->a = array('parent', 'a');
$this->c = array('self', 'c');
  }
  static function c() {
print_r(func_get_args());
  }
  function d() {
call_user_func_array($this->c, func_get_args());
  }
  function e() {
call_user_func($this->c, func_get_args());
  }
}
$a =& new A;
$b =& new B;
$i = 0;
A::a('index', $i);
$a->b('index', $i);
$a->c('string');
$a->d('string');
$a->e('string');
# etc.
?>


Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial