php递归变量不会改变

标签 php

我有这样的功能:

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/

相关文章:

php - 字符在数据库中显示不正确

多个域的PHP临时上传目录

php - 如何使单词的第一个字符大写?

php - 使用 FPDF 自动调整单元格宽度和文本宽度

php - Mysql Php varios 表分页

javascript - PHP 和 Ajax : manage list update

javascript - 从通过 echo 语句动态添加的表单元素获取 POST 值?

php - 设置从本地主机到服务器的服务器代码

php - PHP 在不相关的代码上浪费了多少资源(如果有的话)?

javascript - 使用一个 php 函数返回多个 json 对象