2009年11月14日星期六

PHP call_user_func和call_user_func_array详解

call_user_func 函数类似于一种特别的调用函数的方法,使用方法如下:
[php]
function a($b, $c) {
echo $b;
echo $c;
}
call_user_func('a', "111","222");
call_user_func('a', "333","444");
[/php]

//显示 111 222 333 444

调用类内部的方法用的是array
[php]
class a {
function b($c) {
echo $c;
}
}
call_user_func(array("a", "b"), "111");
[/php]
//显示 111

call_user_func_array 函数和 call_user_func 很相似,只不过是换了一种方式传递了参数,让参数的结构更清晰:
[php]
function a($b, $c) {
echo $b;
echo $c;
}
call_user_func_array('a', array("111", "222"));
[/php]
//显示 111 222

call_user_func_array 函数也可以用于调用类内部方法
[php]
Class ClassA {
function bc($b, $c) {
$bc = $b + $c;
echo $bc;
}
}
call_user_func_array(array('ClassA','bc'), array("111", "222"));
[/php]
//显示 333

call_user_func 函数和 call_user_func_array 函数支持引用
[php]
function a(&$b) {
$b++;
}
$c = 0;
call_user_func('a', &$c);
echo $c; //显示 1
call_user_func_array('a', array(&$c));
echo $c; //显示 2
[/php]
PHP手册上关于这两个函数的定义:
mixed call_user_func (callback function [, mixed parameter [, mixed ...]])

Call a user defined function given by the function parameter. Take the following:

[php]
function barber($type) {
echo "You wanted a $type haircut, no problem";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
[/php]
Object methods may also be invoked statically using this function by passing array($objectname, $methodname) to the function parameter.
[php]
class myclass {
function say_hello() {
echo "Hello!\n";
}
}

$classname = "myclass";

call_user_func(array($classname, 'say_hello'));
[/php]

注: Note that the parameters for call_user_func() are not passed by reference.
[php]
function increment(&$var) {
$var++;
}

$a = 0;
call_user_func('increment', $a);
echo $a; // 0

call_user_func_array('increment', array(&$a)); // You can use this instead
echo $a; // 1
[/php]

mixed call_user_func_array( callback function, array param_arr )
Call a user defined function given by function, with the parameters in param_arr. For example:

call_user_func_array() example
[php]
function debug($var, $val) {
echo "***DEBUGGING\n VARIABLE: $var\nVALUE:";
if (is_array($val) || is_object($val) || is_resource($val)) {
print_r($val);
} else {
echo "\n$val\n";
}
echo "***\n";
}

$c = mysql_connect();
$host = $_SERVER["SERVER_NAME"];

call_user_func_array('debug', array("host", $host));
call_user_func_array('debug', array("c", $c));
call_user_func_array('debug', array("_POST", $_POST));
[/php]
这篇其实转载的(不好意思,忘了是来自哪...)上面有提到说,最后的这个函数有点相当于重载,看了下,确实有那么点重载的意思...

没有评论:

发表评论