How PHP uses recursive functions to achieve numerical summation

Source: Internet
Author: User
What are the methods for implementing recursive functions? How to use recursive function to realize the number accumulation? This article mainly introduces PHP recursive function three implementation methods and how to achieve digital accumulation, the need for friends can refer to.

Recursive function is a kind of common function in programming, its feature is that function itself can call itself, but it must have conditional judgment before invoking itself, otherwise it will cause infinite call down. This article lists three recursive function implementation methods, the first use of reference to do parameters, the second use of global variables, the third use of static variables, to understand this kind of problem needs a bit of foundation, including the global variables, references, static variables of understanding, but also need to understand their scope of action. In this no nonsense, specific introduction please see below.

The first approach: using references to make parameters

First of all, regardless of the reference do not do parameters, you must first understand what is the reference? A reference simply refers to a variable of two different names pointing to the same storage address. Each variable has its own storage address, and the assignment deletes the lines.

Now, two variables share a single storage address. $a =& $b; 。 In fact, $a regardless of their original storage address, do not want to share a room with the $b . Therefore, any change to the value of the stored address will affect both values.

Functions are inherently fragmentation, even for functions with the same name. The recursive function is to consider the reference as a parameter, to become a bridge, to form a data share between two functions. Although the two functions seem to operate on a different address, the actual operation is a memory address.

The code is as follows:

function test ($a =0,& $result =array ()) {$a ++;if ($a <10) {    $result []= $a;    Test ($a, $result);} echo $a; return $result;}

The above example is a very simple answer, with a<10 as a condition, the condition is set, then assigns a to result[]; passing the reference of result to a function adds each recursive result of a to the resulting array of results. Thus, the $result array generated by this example is arrays ([0] = 1 [1] = 2 [2] = 3 [3] = 4 [4] = 5 [5] = 6 [6] => 7 [7] = 8 [8] = 9).

The interesting thing about this example is the value of echo a . I believe many people think it is 12345678910 , but it is 1098765432. Why is it? The next recursive function is performed because the function has not executed echo a.

The true echo a is when the a<10 condition is not satisfied,echo a, returns result, for the previous level, executes the recursive function, starts to perform this layer's echo $a, and so on.

Second approach: Take advantage of global variables

Using global variables to complete the recursive function, make sure you do understand what global variables are . Global declares that a variable is simply a reference to an external variable with the same name. The scope of the variable is still within the scope of this function. Changing the values of these variables, the value of the external variable with the same name has changed naturally. But once &is used, the variable with the same name is no longer referenced by the same name. Using global variables to implement recursive functions it is not necessary to understand such a deep layer, but also to maintain the original view of global variables can logically understand the recursive function.

The code is as follows:

function test ($a =0, $result =array ()) {    global $result;    $a + +;    if ($a <10) {        $result []= $a;        Test ($a, $result);    }    return $result;}

Third approach: using static variables

We often see staticin classes, and today we use it in recursive functions. Remember the function of static: Initializes the variable only the first time it is called, and retains the value of the variable.

  Give me a chestnut:

The code is as follows:

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

What is the execution result of this section of code? Is it 00000 ? Not necessarily. It's 01234. First Call test (), static $count initialization, after each execution will retain the value of $count , no longer initialized, the equivalent of directly ignored static $count =0; This sentence.

Thus it is conceivable to apply static to the function of recursion. Variables that need to be "bridges" between recursive functions are initialized with static , and each recursion retains the value of the bridge variable .

The code is as follows:

function test ($a =0) {    static $result =array ();    $a + +;    if ($a <10) {        $result []= $a;        Test ($a);    }    return $result;}


The so-called recursive function, the focus is how to deal with the function call itself is how to ensure that the required results can be reasonably "passed" between functions, of course, there is no need to pass the function between functions worthy of recursive functions, for example:

The code is as follows:

function test ($a =0) {    $a + +;    if ($a <10) {        echo $a;        Test ($a);}    }

Here's a piece of code that demonstrates how PHP uses recursive functions to accumulate numbers.

The code looks like this:

The code is as follows:

<?phpfunction summation ($count) {if ($count! = 0): return $count + Summat   Ion ($count-1); endif;} $sum = summation (Ten);p rint "summation = $sum";? 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.