有人能给我解释一下这个函数到底是怎么回事吗?
function f($b=0)
{
echo $b.',';
/*otuput is 0,1,2,3,4,5,3,4,2,3,4,5,3,*/
if ($b<3)
{
/*echo $b.',';
when echo is here, otuput is 0,1,2,2,*/
for ($a=0;$a<3;$a++)
{
/*echo $b.',';
when echo is here, otuput is 0,1,2,3,4,2,3,1,2,3,4,2,*/
f(++$b);
}
}
}
f();
为什么输出不是0,1,2,0,1,2,0,1,2,
?以及如何处理从函数中调用相同的函数?
发布于 2018-12-19 04:51:40
首先,它调用f(0)
,所以它显示0
。
然后分别调用f(1)
、f(2)
和f(3)
。
f(1)
:显示1
并运行f(2)
、f(3)
和f(4)
。
f(2)
:显示2
并运行f(3)
、f(4)
和f(5)
。
f(3)
:仅显示3
f(4)
:仅显示4
f(5)
:仅显示5
..。
所以:
f(0):
{
0,
f(1):
{
1,
f(2):
{
2,
f(3):
{
3
},
f(4):
{
4
},
f(5):
{
5
}
},
f(3):
{
3
},
f(4):
{
4
}
},
f(2):
{
2,
f(3):
{
3
},
f(4):
{
4
},
f(5):
{
5
}
},
f(3):
{
3
}
}
所以输出是:0,1,2,3,4,5,3,4,2,3,4,5,3,
发布于 2018-12-19 04:55:26
这是递归的效果。变量b
始终在函数的局部作用域内。当您第一次启动该函数时,b
值为0,因此达到for。++b
语法意味着b在求值之前是递增的,因此当使用b == 0
到达f(++b)
时,它就变成了f(1)
。然后,该函数使用b == 1
开始循环,并到达for。此时,与您预期的相反,当您开始新的递归循环时,您有第一个for仍然等待递归完成。对于下一次使用b==2
的递归,也会发生这种情况。因此,使用一些缩进来澄清循环:
// Prints 0
for ($a = 0; $a < 3; $a++)
f(++$b) // $b == 0, $a == 0
// Prints 1
for ($a = 0; $a < 3; $a++)
f(++$b) // $b == 1, $a == 0
// Prints 2
for ($a = 0; $a < 3; $a++)
f(++$b) // $b == 2, $a == 0
// Prints 3, no further cycles
f(++$b) // $b == 3, $a == 1
// Prints 4, no further cycles
f(++$b) // $b == 4, $a == 2
// Prints 5, no further cycles
// The function returns having completed the cycle
f(++$b) // $b == 2, $a == 1
// Prints 3, no further cycles
f(++$b) // $b == 3, $a == 2
// Prints 4, no further cycles
// The function returns having completed the cycle
f(++$b) // $b == 1, $a == 1
// Etc. etc.
https://stackoverflow.com/questions/53840251
复制相似问题