函数调用时递归函数调用值不保留函数调用时
问题描述:
如果我们使用递归函数调用如何为变量分配内存。当运行下面的代码时,它的回声2作为结果。任何人都可以请指导为什么$ a的值没有采取任何循环迭代。 如果我设置函数调用时递归函数调用值不保留函数调用时
$a= recursionfunction($a);
与在函数中它将工作正常。
function recursionfunction($a)
{
if($a<10)
{
$a=$a+1;
recursionfunction($a);
}
return $a;
}
$result = recursionfunction(1);
echo $result
答
假设你的意思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;
}
$ result = abc(1); - 显然你有一些复制和粘贴奇怪的事情。 –
你的'if'部分不会返回任何东西。另外,我们可以安全地假设'abc()'和'recursionfunction()'是一样的吗? – geomagas