search
HomeDaily ProgrammingPHP KnowledgePHP recursive algorithm (2)

PHP recursive algorithm (2)

Mar 05, 2019 am 11:27 AM
php recursive algorithm

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

PHP recursive algorithm (2)

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

代码如下:

<?php
$i=1;
function call(){
    global $i;
    echo $i;
    $i++;
    if($i<=10){
        call();
    }
}
call();

输出:

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools