php匿名函数

匿名函数(Anonymous functions),也叫闭包函数(closures),允许 临时创建一个没有指定名称的函数。最经常用作回调函数(callback)参数的值。当然,也有其它应用的情况。

匿名函数目前是通过 Closure 类来实现的。

<?php
$message = 'hello';

// 没有 "use"
$example = function () {
    var_dump($message);
};
echo $example();    //Notice: Undefined variable: message in D:\ProgramFiles\phpStudy\WWW\niming.php on line 6      NULL // 继承 $message
$example = function () use ($message) {
    var_dump($message);
};
echo $example();    //string(5) "hello"

// Inherited variable's value is from when the function
// is defined, not when called
$message = 'world';
echo $example();    //string(5) "hello"

// Reset message
$message = 'hello';

// Inherit by-reference
$example = function () use (&$message) {
    var_dump($message);
};
echo $example();        //string(5) "hello"

// The changed value in the parent scope
// is reflected inside the function call
$message = 'world';
echo $example();       //string(5) "world"

// Closures can also accept regular arguments
$example = function ($arg) use ($message) {
    var_dump($arg . ' ' . $message);
};
$example("hello");  //string(11) "hello world"
?>

 

posted on 2018-12-25 16:24  爱吃柠檬不加糖  阅读(285)  评论(0编辑  收藏  举报

导航