Home > Backend Development > PHP Tutorial > How to use static variables in PHP functions

How to use static variables in PHP functions

php中世界最好的语言
Release: 2023-03-22 07:26:02
Original
3567 people have browsed it

This time I will bring you PHP functionstaticHow to use variables, what are the precautions for using PHP function static variables, the following are practical cases , let’s take a look.

In PHP, in addition to the static members properties of classes, static can also be used to define static variables in functions. This makes it easy to complete function iteration.

Example 1:

<?php
function Test()
{
  $a = 0;
  echo $a;
  $a++;
}
?>
Copy after login

In the above example, every time the Test function is called, a is reassigned to 0, because once the function exits, the variable a is is reassigned to 0, because variable a no longer exists once this function exits. To complete the iteration, you need to write a counting function that will not lose the current count value. You need to define the variable $a as static:

<?php
function test()
{
  static $a = 0;
  echo $a;
  $a++;
}
?>
Copy after login

In this way, $a is only assigned the value when it is called for the first time, and then Incremented by 1 on each call and will not be overridden.

In this way, you can use this feature to iterate a specified number of times for an operation:

Example 2: (Get the result after popping 5 elements out of an array)

$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);
Copy after login

Run results:

array(5) {
 [0]=>
 int(1)
 [1]=>
 int(2)
 [2]=>
 int(3)
 [3]=>
 int(4)
 [4]=>
 int(5)
}
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

mysqld_multi deployment stand-alone detailed explanation

Vue production picture carousel

JS gets the value in the first element in the select drop-down box

The above is the detailed content of How to use static variables in PHP functions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template