摘要:<?phpecho '匿名函数可以当做局部变量、函数参数、函数返回值来使用';//1.当做局部变量来使用$fun1=function(){$name='王楚';$test= function() use ($name){ return '我是'.$name;} &n
<?php
echo '匿名函数可以当做局部变量、函数参数、函数返回值来使用';
//1.当做局部变量来使用
$fun1=function(){
$name='王楚';
$test= function() use ($name){
return '我是'.$name;
}
return $test(); //调用,必须执行一次才能形成闭包
}
echo $fun1();
//2.匿名函数当做函数参数
$name2=杨过';
$test2=function() use ($name2){
return $name2.'是个大侠';
}
$fun2=function(callable $test2){
return $test2();
}
echo $fun2();
//3.匿名函数当做函数返回值
$fun3=function(){
$name3=杨康';
$test3=function() use ($name3){
return '杨过是'.$name3.'的儿子';
}
return $test3;
}
echo $fun3()();
?>