閉包可以從父作用域中繼承變量。 任何此類變量都應該用 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