我需要使用以下结构制作PHP程序:
function start(){
$n = 0;
$then = function() use ($n){
++$n;
echo '$n was increased by 1<br />';
};
$then();
echo '$n = '.$n;
}
start();
如果你运行它,你会得到:
$n was increased by 1
$n = 0
我想得到$ n = 1,因为它应该......
$n was increased by 1
$n = 1
要求非常严格:$ n必须在start()函数内声明,$ then函数必须是anonymus,$ n不能作为参数传递。
这可能吗?
答案 0 :(得分:1)
如果你在$ then函数(&amp; $ n)中使用$ n作为参考,它将起作用:
function start(){
$n = 0;
$then = function() use (&$n){
++$n;
echo '$n was increased by 1<br />';
};
$then();
echo '$n = '.$n;
}
start();
有关参考资料的更多信息,请访问:http://php.net/manual/en/language.references.php