Home  >  Article  >  Backend Development  >  PHP recursion cannot return the problem, the correct way to write recursion

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

不言
不言Original
2018-04-20 11:36:281549browse

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();
    }
}


#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();
    }
}

Quotation writing

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

Static variable

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

digui();
digui();
digui();
digui();
digui();

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();

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!

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