PHP uses a function static variable to implement a specified number of iterations steps

Source: Internet
Author: User
This time for you to bring PHP to use the function static variable implementation of the specified number of iterations steps in detail, PHP use the function static variables to achieve the specified number of iterations of the attention of the matter, the following is the actual case, take a look.

In PHP, in addition to the static member properties of a class, static variables can also be defined in a function using static. Thus, the function iteration can be completed conveniently.

Example 1:

<?phpfunction Test () {  $a = 0;  echo $a;  $a + +;}? >

In the above example, each time the test function is called, A is re-assigned a value of 0 because the variable a is re-assigned to 0 once exiting the function, because the variable a does not exist once the function exits. To complete the iteration, you need to write a count function that does not lose the count value, and define the variable $a as static:

<?phpfunction Test () {  static $a = 0;  echo $a;  $a + +;}? >

This way, $ A is only assigned at the first call and then 1 on each call and is not overridden.

This allows you to use this attribute to iterate over a specified number of times for an operation:

Example 2:(Gets the result of ejecting an array of 5 elements)

$arr = Range (1,10,1), function test ($arr) {  static $count =0;  Array_pop ($arr);  $count + +;  if ($count < 5) {    test ($arr);  } else{    var_dump ($arr); exit;}  } Test ($arr);

Operation Result:

Array (5) {[0]=> int (1) [1]=> int (2) [2]=> int (3) [3]=> int (4) [4]=> int (5)}

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:

PHP implementation of the single sign-on steps detailed

PHP based on anti-Ajax push implementation of real-time message push steps

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: info-contact@alibabacloud.com 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.