匿名函数(闭包函数) 允许临时创建一个 没有指定名称的函数 最经常用作回调函数(callback) 参数的值
闭包函数可以作为变量的值来使用
$example = function () {
echo 'Hello <br>' ;
} ;
$example() ;
//闭包函数使用 父作用域变量 use() 使用use()接收变量需要在闭包定义之前定义 或者use(&$message)
$message = 'beijing' ;
$example2 = function () use($message){
echo 'welcome to ' . $message . '<br>';
};
$message = 'shanghai' ;
$example2() ;
$example3 = function (){
global $message ;
echo 'welcome to ' . $message . '<br>';
} ;
$message = 'shanghai' ;
$example3() ;
//常规参数 + 父域参数(&$local 不引用地址的话 $local变量需要在闭包定义之前定义)
$example4 = function ($str) use(&$local){
echo $str . $local . '<br>' ;
} ;
$local = 'beijing' ;
$example4('welcome to ') ;
//闭包函数作为函数参数使用
function test_close($name, $r) {
echo "hello {$name} <br>" ;
$r() ;
}
test_close('zhangsan',function () {
echo 'Redirect to login page' ;
}) ;