PHP 匿名函数中的作用域问题
PHP scope issue in anonymous function
所以我有这些功能
function a(){
int c = 1;
b(function(){echo $c;});
}
function b($code){
$code();
}
但不知何故 $c 在匿名函数中变成未定义
我知道这是因为匿名函数是它自己的范围,但是有什么办法可以让它工作吗?
是:您可以使用 "use" 语句。
function a()
{
$c = 1;
b(function() use ($c) {
echo $c;
});
}
function b($code){
$code();
}
http://php.net/manual/en/language.variables.scope.php
当您将 $c
放入函数中时,它被认为是一个 local scope
变量。
所以我有这些功能
function a(){
int c = 1;
b(function(){echo $c;});
}
function b($code){
$code();
}
但不知何故 $c 在匿名函数中变成未定义 我知道这是因为匿名函数是它自己的范围,但是有什么办法可以让它工作吗?
是:您可以使用 "use" 语句。
function a()
{
$c = 1;
b(function() use ($c) {
echo $c;
});
}
function b($code){
$code();
}
http://php.net/manual/en/language.variables.scope.php
当您将 $c
放入函数中时,它被认为是一个 local scope
变量。