参考:
https://www.zhihu.com/question/28062458
<?php $a = 'aac'; $say = function () use (&$a) { echo $a; }; $a = "zzzzzzzzzzz"; //$say(); //$fib = function($n) use(&$fib){ // if ($n < 2) { // return 1; // } // return $fib($n-1) + $fib($n-2); //}; //echo $fib(22); function fib($n) { if ($n < 2) { return 1; } return fib($n-1) + fib($n-2); } $t1 = microtime(true); var_dump(fib(40)); var_dump(fib(41)); $t2 = microtime(true); $fib = array(); $fib[0] = 1; $fib[1] = 1; for ($i = 2; $i < 42; $i++) { $fib[$i] = $fib[$i-1] + $fib[$i-2]; } $t3 = microtime(true); var_dump($fib[40]); var_dump($fib[41]); echo "t2-t1:" . round($t2-$t1, 7)." "; echo "t3-t2:" . round($t3-$t2, 7)." ";
----------------------------
PHP 匿名函数 function use 与直接传参的区别
https://blog.csdn.net/gezipml/article/details/83069561
<?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"); ?>
-------------------------------------------------------
解除递归函数
-
-
$fib = function($n) use(&$fib) {
-
if($n == 0 || $n == 1) return 1;
-
return $fib($n - 1) + $fib($n - 2);
-
};
-
-
echo $fib(2) . " "; // 2
-
$lie = $fib;
-
$fib = function(){die('error');};//rewrite $fib variable
-
echo $lie(5); // error because $fib is referenced by closure
注意上题中的use使用了&,这里不使用&会出现错误$fib($n-1)是找不到function的(前面没有定义fib的类型)
所以想使用闭包解除循环函数的时候就需要使用
-
-
$recursive = function () use (&$recursive){
-
// The function is now available as $recursive
-
}
这样的形式
4 关于延迟绑定
如果你需要延迟绑定use里面的变量,你就需要使用引用,否则在定义的时候就会做一份拷贝放到use中
-
-
$result = 0;
-
-
$one = function()
-
{ var_dump($result); };
-
-
$two = function() use ($result)
-
{ var_dump($result); };
-
-
$three = function() use (&$result)
-
{ var_dump($result); };
-
-
$result++;
-
-
$one(); // outputs NULL: $result is not in scope
-
$two(); // outputs int(0): $result was copied
-
$three(); // outputs int(1)
使用引用和不使用引用就代表了是调用时赋值,还是申明时候赋值