为什么要存在回调函数,在网络编程,尤其是我们的php的编程技术里面貌似没有什么用,它不是事件驱动的随时性调用。但是有这样一种情况,当我们的系统做好之后,你需要完成某个过程后再调用函数,因为系统已经做好了,你不可能知道用户在扩展的时候用什么函数,事实上这时候用户的函数都是自定义的,为了能够调用这些自定义的函数,在编程技术里面就有了回调函数。
call_user_func 函数存在的版本(PHP 4, PHP 5)
函数的原型:
mixed call_user_func ( callback $function [, mixed $parameter [, mixed $... ]] )
$function:即是我们需要回调函数的名称
mixed $parameter:后面接的都是回调函数的参数
返回值:回调函数的结果或者FALSE
1、回调普通函数:
例子:
function barber($type)
{
echo "You wanted a $type haircut, no problem\n";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
运行结果:
You wanted a mushroom haircut, no problem
You wanted a shave haircut, no problem
2、回调namespace的函数:
namespace Foobar;
class Foo {
static public function test() {
print "Hello world!\n";
}
}
call_user_func(__NAMESPACE__ .'\Foo::test'); // As of PHP 5.3.0
call_user_func(array(__NAMESPACE__ .'\Foo', 'test')); // As of PHP 5.3.0
?>
关于namespace是为了区别函数或者类重名而生的,至于以后会不会有import就难说了。
3、回调类的函数或者方法
class myclass {
static function say_hello()
{
echo "Hello!\n";
}
}
$classname = "myclass";
call_user_func(array($classname, 'say_hello'));
call_user_func($classname .'::say_hello'); // As of 5.2.3
$myobject = new myclass();
call_user_func(array($myobject, 'say_hello'));
?>
这个有几点要说明的是:
1、php的回调类的函数只能是静态函数
2、回调类的函数第一个参数是一个数组array(类名, 函数名)
3、在5.2.3后支持第一参数这么写$classname .’::say_hello’;
4、回调即刻构造的函数:
call_user_func(function($arg) { print "[$arg]\n"; }, 'test'); /* As of PHP 5.3.0 */
?>
这个是最新的写法,在5.3.0后的,不过貌似没有什么用,不如写个函数了,函数代码很多多麻烦啊。
一些注意事项:
1.如果前一次的回调有问题的话,那么后面的回调函数就不会执行了。
2.要验证传入的参数是否正确is_callable() 函数。
3.参数传递用数组如$pipes,而不是$pipes[0], $pipes[1], $pipe[2]。
好了,至此回调函数已完,你问我能做什么?如递归等,最重要的是worpress因为有了它hook即钩子的思想就出来,为开发插件立下汗马功劳啊。