call_user_func和call_user_func_array

来源:互联网 发布:网易邮箱 数据库下载 编辑:程序博客网 时间:2024/05/22 16:01
常用的两个回调函数的:call_user_func和call_user_func_array
mixed call_user_func ( callback function [, mixed parameter [, mixed ...]] ):
利用第一个参数回调用户的函数

利用给定函数的参数来调用一个用户定义的函数:
Call a user defined function given by the function parameter. Take the following:
例子:
function barber($type)
{
   echo "You wanted a $type haircut, no problem";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");

类的方法也可以通过传递参数"array(类名,方法名)"的方式静态调用.
Class methods may also be invoked statically using this function by passing array($classname, $methodname) to the function parameter.
例如:
class myclass {
   function say_hello()
   {
       echo "Hello!\n";
   }
}

$classname = "myclass";

call_user_func(array($classname, 'say_hello'));

注意:
call_user_func()的参数不是以引用的方式传递的。(???????)
Note that the parameters for call_user_func() are not passed by reference.

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
//这个例子能说明什么问题??我只看到call_user_func_array也不是以引用的方式传递的。
//并且,如果类似的把call_user_func_array('increment', array(&$a));的第二个参数
//换成:array($a)的话,$a也是不改变的。同理,如果把 call_user_func('increment', $a);
//的第二个参数换成&$a的话,$a的值也是会+1的。



mixed call_user_func_array ( callback function, array param_arr )
:Call a user function given with an array of parameters

调用一个用户定义的函数,参数以('函数名','函数参数数组')的方式定义。
Call a user defined function given by function, with the parameters in param_arr. For example:

function debug($var, $val)
{
   echo "***DEBUGGING\nVARIABLE: $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));