闭包可以从父作用域中继承变量。 任何此类变量都应该用 use 语言结构传递进去。
PHP的闭包即为匿名函数。
示例如下。
$message = 'hello';
// 继承 $message
$example = function () use ($message) {
var_dump($message);
};
echo $example(); //hello
// Inherited variable's value is from when the function
// is defined, not when called
//use继承的变量值是函数定义时的变量值,而不是调用时的变量值
$message = 'world';
echo $example(); //hello
// Reset message
$message = 'hello2';
// Inherit by-reference
//通过引用继承,则可以获取到变量的变化值。
$example = function () use (&$message) {
var_dump($message);
};
echo $example(); //hello2 引用地址
// 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