编辑:很抱歉,当我试图找出问题时,原始代码是一个迭代,我已经编辑了代码 This问题开始类似,但这是我遇到的真正问题:
在这段代码中:
<?php
$a = 2:
function incr(){
$a++;
echo $a;
}
echo $a;
incr();
?>
输出是 2,然后是 1,这向我表明变量 $a
在函数内部被初始化为 0。服务器是否仅凭我使用增量语法将变量初始化为 0 就知道了?
最佳答案
$a
未定义,然后当您递增它时,它会变为 1
。
function incr(){
$a++; // $a is undefined
return $a;
}
正如 manual 中指出的那样:
Note:
The increment/decrement operators only affect numbers and strings. Arrays, objects and resources are not affected. Decrementing NULL values has no effect too, but incrementing them results in 1.
您可以使用 global
,它会按预期返回。
function incr(){
global $a;
$a++;
return $a;
}
关于php - 函数内部变量 incremented 的值为 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24149339/