Home > Article > Backend Development > PHP recursion cannot return the problem, the correct way to write recursion
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
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(); } }
function digui($tiaojian,&$result){ if ($tiaojian) { $result=$data; } else{ digui(); } }
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!