Home  >  Article  >  Backend Development  >  What is recursion in PHP? What are the ways to achieve this?

What is recursion in PHP? What are the ways to achieve this?

王林
王林Original
2019-11-12 17:54:513050browse

What is recursion in PHP? What are the ways to achieve this?

What is recursion

Recursion: A programming method in which a function calls itself, similar to a loop, so the function called recursively must There is a termination condition, otherwise it will become an infinite loop.

Commonly used methods of recursion:

1. Static variable method

function loop(){
 static $i = 0;
 echo $i.' ';
 $i++;
 if($i<10){
     loop();
 }
}
loop();//输出 0 1 2 3 4 5 6 7 8 9

2. Global variable method

$i = 0;
function loopGlobal(){
  global $i;
 echo $i.&#39; &#39;;
 $i++;
 if($i<10){
    loopGlobal();
 }
}
loopGlobal();//输出 0 1 2 3 4 5 6 7 8 9

3. Reference parameter passing method

function loopReference(&$i=0){
 echo $i.&#39; &#39;;
 $i++;
 if($i<10){
  loopReference($i);
 }
}
loopReference();//输出 0 1 2 3 4 5 6 7 8 9

Recommended tutorial: PHP tutorial

The above is the detailed content of What is recursion in PHP? What are the ways to achieve this?. 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