好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

PHP匿名函数可以干什么用

匿名函数(Anonymous functions),也叫闭包函数(closures),允许临时创建一个没有指定名称的函数。

匿名函数的好处

1、非匿名函数在定义时就创建函数对象和作用域对象,以后及时未调用,也占空间

2、匿名函数只有在调用时,才会创建函数对象和作用域对象。调用完后立即释放,节省内存。

php中匿名函数的使用

1、作为回调函数使用

<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');
// 
输出 helloWorld

2、作为变量赋值

<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');

输出:

3、 从父作用域继承变量

<?php
$message = 'hello';
// 没有 "use"
$example = function () {
    var_dump($message);
};
echo $example();
// 继承 $message
$example = function () use ($message) {
    var_dump($message);
};
echo $example();

输出:

以上就是PHP匿名函数可以干什么用的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于PHP匿名函数可以干什么用的详细内容...

  阅读:60次