PHP函数(六)-匿名函数(闭包函数)

匿名函数能够临时创建一个没有名称的函数,常用作回调函数参数的值

<?php
	$test = function($a){
		echo "Hello,".$a;
	};
	$test("world");
?>

一定要在匿名函数的结尾处加上分号

执行结果

回调函数将匿名函数做参数

<?php
	function callback($a){
		$a();
	}
	
	callback(function(){ //声明一个匿名函数并传给callback()函数
		echo "test";
	});
?>

 执行结果

引用外部变量

<?php
	function callback($a){
		$a();
	}
	
	$str = "php";
	
	callback(function() use ($str){ //通过use关键字来引用外部变量
		echo $str." test";
	});
?>

use引用的为外部变量的副本,要想完全引用,要在前面加上&,如

callback(function() use (&$str){});
原文地址:https://www.cnblogs.com/sch01ar/p/8127882.html