[PHP] PHP闭包(closures)

1.闭包函数也叫匿名函数,一个没有指定名称的函数,一般会用在回调部分
2.闭包作为回调的基本使用,
echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');

第三个参数是要匹配的目标字符串,第二个参数是一个匿名函数,当preg_replace_callback执行的时候,会回调匿名函数,并且把匹配到的结果,作为匿名函数的参数传递进去

3.闭包函数变量赋值的使用
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};
$greet('World');
闭包函数赋值给了一个变量,这个变量直接跟()小括号就是执行这个函数,小括号里面的参数会传递到闭包函数里面去

4.闭包函数从父作用域继承变量的使用
$message = 'hello';
$example = function () use ($message) {
    var_dump($message);
};
$example();
使用use关键字把函数外面的父作用域的变量传递到了函数里面

5.闭包函数变量赋值+()执行函数传递参数+use()关键字传递父作用域变量
$message="taoshihan";
$example = function ($arg) use ($message) {
    var_dump($arg . ' ' . $message);
};
$example("hello"); //输出string(15) "hello taoshihan"

 

posted @ 2018-11-27 22:10  唯一客服系统开发笔记  阅读(507)  评论(0编辑  收藏  举报