PHP匿名函数(闭包函数)
PHP 匿名函数(Anonymous functions)也叫闭包函数(closures),允许临时创建一个没有指定名称的函数,经常用作回调函数(callback)参数的值。当然,也有其他应用的情况。
PHP 匿名函数的使用示例如下:
闭包函数也可以作为变量的值来使用,PHP 会自动把此种表达式转换成内置类 closure 的对象实例。把一个 closure 对象赋值给一个变量的方式与普通变量赋值的语法是一样的,最后也要加上分号
闭包可以从父作用域中继承变量,这时需要使用关键词 use,示例如下:
PHP 匿名函数的使用示例如下:
<?php
echo preg_replace_callback('~-([a-z])~', function($match){
return strtoupper($match[1]);
}, 'hello-world');
?>
上面示例中,preg_replace_callback() 函数接收的第一个参数为正则表达式,第二个参数为回调函数,第三个参数为所要匹配的元素。闭包函数也可以作为变量的值来使用,PHP 会自动把此种表达式转换成内置类 closure 的对象实例。把一个 closure 对象赋值给一个变量的方式与普通变量赋值的语法是一样的,最后也要加上分号
:,示例如下:
<?php
$greet=function($name){
echo "hello $name \n";
};
$greet('World');
$greet('PHP');
?>
以上程序的执行结果为:hello World hello PHP。闭包可以从父作用域中继承变量,这时需要使用关键词 use,示例如下:
<?php
$message='hello';
//没有"use"
$example=function(){
var_dump($message);
};
echo $example(); //输出值为 null
//继承$message
$example=function()use($message){
var_dump($message);
};
echo $example(); //输出结果hello
//当函数被定义的时候就继承了作用域中变量的值, 而不是在调用时才继承
//此时改变 $message 的值对继承没有影响
$message='world';
echo $example(); // 输出结果hello
//重置 $message 的值为"hello"
$message='hello';
// 继承引用
$example=function()use(&$message){
var_dump($message);
};
echo $example(); //输出结果 hello
// 父作用域中 $message 的值被改变, 当函数被调用时$message的值发生改变
// 注意与非继承引用的区别
$message='world';
echo $example(); // 输出结果 world
// 闭包也可接收参数
$example=function($arg)use($message){
var_dump($arg.''.$message);
};
$example("hello"); // 输出结果 hello world
?>
以上程序的执行结果为:
NULL string(5) "hello" string(5) "hello" string(5) "hello" string(5) "world" string(11) "hello world”
所有教程
- socket
- Python基础教程
- C#教程
- MySQL函数
- MySQL
- C语言入门
- C语言专题
- C语言编译器
- C语言编程实例
- GCC编译器
- 数据结构
- C语言项目案例
- C++教程
- OpenCV
- Qt教程
- Unity 3D教程
- UE4
- STL
- Redis
- Android教程
- JavaScript
- PHP
- Mybatis
- Spring Cloud
- Maven
- vi命令
- Spring Boot
- Spring MVC
- Hibernate
- Linux
- Linux命令
- Shell脚本
- Java教程
- 设计模式
- Spring
- Servlet
- Struts2
- Java Swing
- JSP教程
- CSS教程
- TensorFlow
- 区块链
- Go语言教程
- Docker
- 编程笔记
- 资源下载
- 关于我们
- 汇编语言
- 大数据
- 云计算
- VIP视频