你知道茴香的有四种写法,那你知道 php 的回调也有四种写法吗?

匿名函数

1
2
3
4
var $array = [1,2,3];
array_map(function($item){
  return $item;
},$array);

类静态调用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class A
{
    static function test($req)
    {
        echo "hello world";
    }
}
var $array = [1,2,3];
array_map('A::Test',$array);
array_map(['A','Test'],$array);

函数

1
2
3
4
5
function test($item){
  return 'hello world';
}
var $array = [1,2,3];
array_map('test',$array);

对象方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class A
{
    static function test($req)
    {
        echo "hello world";
    }
}
var $array = [1,2,3];
$obj = new A();
array_map([$obj,'test'],$array);

转载自:4种PHP回调函数风格-Swoole扩展-Swoole文档中心