用外行的话来说是什么是使用 PHP 的递归函数 [英] What in layman's terms is a Recursive Function using PHP
问题描述
任何人都可以用外行语言和示例用 PHP(不使用斐波那契)向我解释递归函数吗?我正在看一个例子,但斐波那契完全失去了我!
Can anyone please explain a recursive function to me in PHP (without using Fibonacci) in layman language and using examples? i was looking at an example but the Fibonacci totally lost me!
提前谢谢你;-)另外,您在 Web 开发中使用它们的频率如何?
Thank you in advance ;-) Also how often do you use them in web development?
推荐答案
外行条款:
递归函数是调用自身
如果函数不断调用自己,它怎么知道什么时候停止?您设置了一个条件,称为基本情况.基本情况告诉我们的递归调用何时停止,否则它将无限循环.
If the function keeps calling itself, how does it know when to stop? You set up a condition, known as a base case. Base cases tell our recursive call when to stop, otherwise it will loop infinitely.
对我来说一个很好的学习例子是 factorial.从下面的评论来看,阶乘函数似乎有点太多了,我会留在这里以防万一.
What was a good learning example for me, since I have a strong background in math, was factorial. By the comments below, it seems the factorial function may be a bit too much, I'll leave it here just in case you wanted it.
function fact($n) {
if ($n === 0) { // our base case
return 1;
}
else {
return $n * fact($n-1); // <--calling itself.
}
}
关于在 Web 开发中使用递归函数,我个人并不使用递归调用.并不是说我认为依赖递归是不好的做法,但它们不应该是您的第一选择.如果使用不当,它们可能会致命.
In regards to using recursive functions in web development, I do not personally resort to using recursive calls. Not that I would consider it bad practice to rely on recursion, but they shouldn't be your first option. They can be deadly if not used properly.
虽然我无法与目录示例竞争,但我希望这会有所帮助.
Although I cannot compete with the directory example, I hope this helps somewhat.
查看这个问题也很有帮助,其中接受的答案用外行术语演示了递归函数的工作原理.尽管 OP 的问题涉及 Java,但概念是相同的,
It would also be helpful to check out this question, where the accepted answer demonstrates in laymen terms how a recursive function works. Even though the OP's question dealt with Java, the concept is the same,
这篇关于用外行的话来说是什么是使用 PHP 的递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!