PHP recursion cannot return the problem, the correct way to write recursion

不言
Release: 2023-03-24 13:42:02
Original
1532 people have browsed it

The content of this article is about the problem that PHP recursion cannot return. The correct way to write recursion has a certain reference value. Now I share it with everyone. Friends in need can refer to it

Conventional writing method

function digui($tiaojian){
    if ($tiaojian) {        return  $data;
    }    else{        return digui();
    }
}
Copy after login


#Note: When the condition is not met, the recursive function must be returned. Otherwise,

cannot be returned normally if the recursion is just for output. Can be abbreviated:

function digui($tiaojian){
    if ($tiaojian) {        echo $data;
    }    else{
        digui();
    }
}
Copy after login

Quotation writing

function digui($tiaojian,&$result){
    if ($tiaojian) {        $result=$data;
    }    else{
        digui();
    }
}
Copy after login

Static variable

function digui(){
    static $count=0;    echo $count;    $count++;
}

digui();
digui();
digui();
digui();
digui();
Copy after login

The output result is: 0 1 2 3 4
Note: The static variable method must be used with caution. Because every time this method is called, the original method that originally defined this variable will be operated on.

Even unset cannot destroy static variables

function digui(){
    static $count=0;    echo $count;    $count++;    unset($count);
}

digui();
digui();
digui();
digui();
digui();
Copy after login

This code still outputs 0 1 2 3

Related recommendations:

php recursion Function instance analysis


The above is the detailed content of PHP recursion cannot return the problem, the correct way to write recursion. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!