【问题标题】:recursive function call value not retaining while function call函数调用时不保留递归函数调用值
【发布时间】:2013-11-06 23:45:13
【问题描述】:

如果我们使用递归函数调用如何为变量分配内存。在代码下面运行时,它的 echo 2 作为结果。谁能指导我为什么 $a 的值不接受任何循环迭代。 如果我设置了

$a= recursionfunction($a); 

在函数中它可以正常工作。

function recursionfunction($a)
{
    if($a<10)
    {
        $a=$a+1;
        recursionfunction($a);

    }
   return $a;

}
$result = recursionfunction(1);
echo $result

【问题讨论】:

  • $result = abc(1); - 很明显,你遇到了一些复制和粘贴的怪异现象。
  • 你的if 部分没有return 任何东西。另外,我们可以安全地假设abc() 与recursionfunction() 相同吗?

标签: php recursion return


【解决方案1】:

假设您的意思是 recursionfunction( 1 ) 而不是 abc( 1 ),则您的函数中缺少 return:

function recursionfunction($a)
{
    if($a<10)
    {
        $a=$a+1;
        return recursionfunction($a);
// missing -^
    }else{
        return $a;
    }

}
$result = recursionfunction(1);
echo $result

编辑

在您进行(大量)编辑之后,整个情况就不同了。 让我们逐行浏览函数,看看会发生什么:

// at the start $a == 1, as you pass the parameter that way.

// $a<10, so we take this if block
    if($a<10)
    {
        $a=$a+1;
// $a now holds the value 2

// call the recursion, but do not use the return value
// as here copy by value is used, nothing inside the recursion will affect
// anything in this function iteration
        recursionfunction($a);
    }

// $a is still equal to 2, so we return that
   return $a;

更多细节可以在这个问题中找到:Are PHP Variables passed by value or by reference?

可能你又想添加一个额外的return 语句,以实际使用递归的值:

function recursionfunction($a)
{
    if($a<10)
    {
        $a=$a+1;
        return recursionfunction($a);
// add ---^
    }
   return $a;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多