在项目中看到这种写法,去手册看了一下实例,开始看的有些晕。
以下是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();
// 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();
// Closures can also accept regular arguments
$example = function ($arg) use ($message) {
var_dump($arg . ' ' . $message);
};
$example("hello");
?>
以上代码输出:
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"
在第三个echo的时候,程序先改变了$message的值,但是输出仍然为 "hello",而非"word"。
由此可见use的参数继承的值是在匿名函数创建的时候就不会再更改了。除非在参数前加 & ,但这样的话跟直接传参没有多大的区别,那么use也没有意义了。