Home  >  Article  >  Daily Programming  >  PHP recursive algorithm (2)

PHP recursive algorithm (2)

藏色散人
藏色散人Original
2019-03-05 11:27:3511944browse

在前面的文章《PHP递归算法(一)》中,我们为大家介绍了如何利用静态变量的方法来实现递归算法。本篇文章我们就继续为大家介绍另一种实现递归算法的方法即通过全局变量的方法。

PHP recursive algorithm (2)

下面我们结合代码示例,为大家介绍通过全局变量Global实现递归的方法。

代码如下:

输出:

12345678910

在上述代码中,如果我们没有在方法体内用global 定义$i,则会出现$i未被声明的错误。并且需要注意,在函数体内定义的global变量,函数体内可以使用,在函数体外定义的global变量不能在函数体内使用。

注:Global的作用是定义全局变量,但是这个全局变量不是应用于整个网站,而是应用于当前页面,包括include或require的所有文件。递归即调用自身的函数。在使用递归时,我们需要在函数中定义退出条件,否则它将进入无限循环(这里我们通过if语句定义了退出条件)。

本篇文章就是关于通过PHP全局变量实现递归算法的方法介绍,非常简单易懂,希望对需要的朋友有所帮助,那么在后续的文章中,我们会继续为大家介绍如何通过引用传参的方式实现递归算法!

The above is the detailed content of PHP recursive algorithm (2). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn