PHP中的闭包和匿名函数
其实再PHP中,闭包和匿名函数是同一样东西。
另外,经常在匿名函数的使用中出现use关键字,对于这个很不理解,所以在网上搜索了一下。
如果没有use
$s = "hello";
$f = function () {
echo $s;
};
$f(); // Notice: Undefined variable: s使用use
$s = "hello";
$f = function () use ($s) {
echo $s;
};
$f(); // hellouse中的变量是在函数定义的时候定义的,而不是在被调用的时候决定的
$s = "hello";
$f = function () use ($s) {
echo $s;
};
$s = "how are you?";
$f(); // hello当然也可以使用&来重新被引用
$s = "hello";
$f = function () use (&$s) {
echo $s;
};
$s = "how are you?";
$f(); // how are you?参考来源:
In PHP, what is a closure and why does it use the “use” identifier?
关于php匿名函数中的use
评论已关闭