php匿名函数怎么写

PHP匿名函数和闭包使用的句法与普通函数相同,但匿名函和闭包数其实是伪装成函数的对象.

匿名函数:

就是没有名称的函数.匿名函数可以赋值给变量,对象传递.不过匿名函数仍是函数,因此可以调用,还可以传入参数.匿名函数特别适合作为函数或方法的回调.

闭包:

是指在创建时封装周围状态的函数.即使闭包所在的环境不存在了,闭包中封装的状态依然存在.

注意:理论上讲,闭包和匿名函数是不同的概念. 不过,PHP将其视作相同的概念.

匿名函数的写法

$func = function(){ 
    
};//带结束符

实例

$func = function ($param) {
     echo($param); 
}; 
 
$func('hello world');

提到匿名函数,就不得不提闭包,将匿名函数放在普通函数中,也可以将匿名函数返回,这就构成了一个简单的闭包

function closureFunc1 () { 
    $func = function () {
         echo "hello"; 
}; $func(); 
} 
 
closureFunc1(); //输出: hello
微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_2808.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?