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 )

PHP code to write to a CSV file from MySQL query

Different versions of PHP - History and evolution of PHP

PHP code to import from CSV file to MySQL

Send push notifications using Expo tokens in PHP

A Basic Example using PHP in AWS (Amazon Web Services)

Encrypting files using GnuPG (GPG) via PHP

PHP Warning: Unknown(): Unable to load dynamic library '/usr/local/php4/lib/php/extensions/no-debug ......

Decrypting files using GnuPG (GPG) via PHP

Parent: child process exited with status 3221225477 -- Restarting

Error: Length parameter must be greater than 0

Convert a hex string into a 32-bit IEEE 754 float number in PHP

Password must include both numeric and alphabetic characters - Magento

Convert XML to CSV in PHP

PHP file upload prompts authentication for anonymous users

Count occurrences of a character in a String in PHP

Latest Articles (in PHP)