闭包函数
创建时封装周围状态的函数,即使闭包所在的环境不存在了,闭包封装的状态依然存在。
匿名函数
没有名称的函数,可以赋值给变量,像PHP对象一样传递;可以调用、传递参数;匿名函数特别适合做函数的回调。
理论上闭包与匿名函数不同,但是在PHP中匿名函数就是闭包函数,创建一个没有函数名称的函数,最常用作函数回调(callback)参数值。
匿名函数通过Closure类实现。
匿名函数示例:
<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
return strtoupper($match[1]);
}, 'hello-world');
// 输出 helloWorld
?>
匿名函数变量赋值示例:
<?php
$greet = function($name)
{
printf("Hello %s\r\n", $name);
};
$greet('World');
$greet('PHP');
?>
从父作用域继承变量
<?php
$message = 'hello';
// 没有 "use"
$example = function () {
var_dump($message);
};
echo $example();
// 继承 $message
$example = function () use ($message) {
var_dump($message);
};
echo $example();
// Inherited variable's value is from when the function
// is defined, not when called
//继承变量的值是从函数时开始的
// 是定义的,而不是在被调用时
$message = 'world';
echo $example();
//输出hello
// Reset message
$message = 'hello';
// Inherit by-reference
$example = function () use (&$message) {
var_dump($message);
};
echo $example();
// The changed value in the parent scope
// is reflected inside the function call
//父范围中更改的值
//反映在函数调用内部
$message = 'world';
echo $example();
//输出world
// Closures can also accept regular arguments
//闭包也可以接受常规参数
$example = function ($arg) use ($message) {
var_dump($arg . ' ' . $message);
};
$example("hello");
//输出hello world
?>
输出示例
Notice: Undefined variable: message in /example.php on line 6
NULL
string(5) "hello"
string(5) "hello"
string(5) "hello"
string(5) "world"
string(11) "hello world"