匿名函数(Anonymous functions),也叫闭包函数(closures),允许 临时创建一个没有指定名称的函数。最经常用作回调函数(callback)参数的值。当然,也有其它应用的情况。
匿名函数目前是通过 Closure 类来实现的。
<?php $message = 'hello'; // 没有 "use" $example = function () { var_dump($message); }; echo $example(); //Notice: Undefined variable: message in D:ProgramFilesphpStudyWWW iming.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" ?>