php递归变量不会改变

时间:2012-02-08 13:11:10

标签: php

我的功能如下:

myfunction($i,$condition = false, $level = 0) {
   do {
      if (... some conditions here)   { myfunction($i, true, ++$level) }
      else { do something here ... }
   while ( ...meet ending condition )
}

我不明白为什么当我以递归方式调用true时$ $条件转为myfunction()并在第一级迭代时返回false并且$level不会退出递归模式后转到0

$condition = false, false, true, false, false, true, true, true ...

$level = 0,0,1,1,1,2,2,2 ... it shoul also be like = 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 )
    }

3 个答案:

答案 0 :(得分:2)

每个执行的函数都有自己的局部变量。顾名思义,这些变量是 local ,而不是在递归调用之间共享。

++运算符递增 local 变量。

答案 1 :(得分:2)

您遗漏的是++$level$level+1之间的差异。前者修改了$level的值,因此在myfunction的同一调用中对该变量的进一步引用会看到递增的值。如果那不是您想要的,请改为编写$level+1

答案 2 :(得分:2)

这种情况正在发生,因为您正在执行++$level,它会增加$level的本地副本,然后将新增加的值传递给函数的递归调用。

尝试将其更改为$level + 1,它只将$value加上一个值传递给函数但不更改变量的本地副本,这样如果函数返回,您仍然拥有旧的联合国 - $value中的增量值。