我有这样的功能:
myfunction($i,$condition = false, $level = 0) {
do {
if (... some conditions here) { myfunction($i, true, ++$level) }
else { do something here ... }
while ( ...meet ending condition )
}
我不明白为什么 $condition 在我递归调用 myfunction()
时变为 true
而在迭代时又返回到 false
第一层和 $level
在退出递归模式后不会变为 0
。
$condition = false,false,true,false,false,true,true,true ...
$level = 0,0,1,1,1,2,2,2 ...它也应该像 = 0,0,1,0,0,1,2,2,2 ,0 ...
等等
?
谢谢
P.S : 数组也一样吗?我在函数中声明了一个数组设置为 null,当退出递归模式时它不再是 null :
myfunction($i,$condition = false, $level = 0, $array = null) {
do {
if($condition) { $array = null } <--------- I HAVE TO ADD THIS LINE TO MAKE IT NULL WHY ?
if (... some conditions here) {$array = Array(someblabla); myfunction($i, true, ++$level, $array) }
else { do something here ... }
while ( ...meet ending condition )
}
最佳答案
您缺少的是 ++$level
和 $level+1
之间的区别。前者修改了 $level
的值,因此在 myfunction
的同一调用中对该变量的进一步引用会看到增加后的值。如果这不是您想要的,请改为编写 $level+1
。
关于php递归变量不会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9193960/