Programming Tutorials

call_user_func() or call_user_func_array() functions in PHP

By: Boards in PHP Tutorials on 2011-10-29  

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.
?>





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

Using Codeigniter for PHP application development

call_user_func() or call_user_func_array() functions in PHP

Reading contents of a File into a String in PHP

PHP INSTALLATION on Solaris 9 (Sparc)

unset() and empty() functions in PHP

isset() function in PHP

PHP pages does not display in IIS 6 with Windows 2003

Parent: child process exited with status 3221225477 -- Restarting

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Retrieve multiple rows from mysql and automatically create a table in PHP

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

Installing PHP with nginx-server under windows

Warning: session_start(): open .... failed - PHP error

Convert IP address to integer and back to IP address in PHP

Latest Articles (in PHP)