用外行的话来说就是使用PHP的递归函数 [英] What in layman's terms is a Recursive Function using PHP

查看:74
本文介绍了用外行的话来说就是使用PHP的递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以用外行语言和示例以PHP(不使用Fibonacci)向我解释递归函数吗?我在看一个例子,但斐波那契完全让我迷失了!

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!

提前谢谢;-) 另外,您在网络开发中多久使用一次?

Thank you in advance ;-) Also how often do you use them in web development?

推荐答案

Laymens条款:

递归函数是调用自身

如果函数不断调用自身,它如何知道何时停止?您设置了一个条件,称为基本情况.基本情况告诉我们递归调用何时停止,否则它将无限循环.

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.

对我来说,因为我在数学方面具有深厚的背景,所以对我来说是一个很好的学习示例,它是阶乘.通过下面的评论,似乎阶乘函数可能有点过多,我将其保留在这里,以防万一您需要它.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆