匿名函数(Anonymous functions),也叫闭包函数(closures),允许临时创建一个没有指定名称的函数。
匿名函数的好处
1、非匿名函数在定义时就创建函数对象和作用域对象,以后及时未调用,也占空间
2、匿名函数只有在调用时,才会创建函数对象和作用域对象。调用完后立即释放,节省内存。
立即学习“PHP免费学习笔记(深入)”;
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匿名函数可以干什么用的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号