Home  >  Article  >  Backend Development  >  How to use static variables in php? Detailed explanation of static variable usage

How to use static variables in php? Detailed explanation of static variable usage

伊谢尔伦
伊谢尔伦Original
2017-06-30 11:30:112360browse

Another important feature of variable scope in php is static variables (static variables). Static variables only exist in the local function domain and are only initialized once. When the program execution leaves this scope, its value will not disappear, and the result of the last execution will be used.

Look at the following example:

<?php 
function Test() 
{ 
$w3sky = 0; 
echo $w3sky; 
$w3sky++; 
} 
?>


This function will set the value of $w3sky to 0 and output "0" every time it is called. Increasing the variable $w3sky++ by one has no effect, because the variable $w3sky does not exist once this function exits. To write a counting function that will not lose this count value, the variable $w3sky must be defined as static:
is as follows:

<?php 
function Test() 
{ 
static $w3sky = 0; 
echo $w3sky; 
$w3sky++; 
} 
?>


This function will count every time it calls Test() Print the value of $w3sky and add one.
Static variables also provide a way to handle recursive functions. A recursive function is a method that calls itself. Be careful when writing recursive functions, as they may recurse indefinitely without an exit. Be sure to have a way to abort the recursion. The following simple function recursively counts to 10, using the static variable $count to determine when to stop:
Example of static variables and recursive functions:

<?PHP 
function Test() 
{ 
static $count = 0; 
$count++; 
echo $count; 
if ($count < 10) { 
Test(); 
} 
$count--; 
} 
?>


Note: Static variables can be used as above Example statement. If it is assigned with the result of expression in the declaration, it will cause a parsing error.
Example of declaring static variables:

<?PHP 
function foo(){ 
static $int = 0;// correct 
static $int = 1+2; // wrong (as it is an expression) 
static $int = sqrt(121); // wrong (as it is an expression too) 
$int++; 
echo $int; 
} 
?>


The above is the detailed content of How to use static variables in php? Detailed explanation of static variable usage. 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