Home  >  Article  >  php教程  >  php中static静态变量的使用方法详解_php基础

php中static静态变量的使用方法详解_php基础

WBOY
WBOYOriginal
2016-05-17 09:01:421581browse

看看下面的实例:

复制代码 代码如下:

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

本函数每次调用时都会将 $w3sky 的值设为 0 并输出 "0"。将变量加一的 $w3sky++ 没有其到效果,因为一旦退出本函数则变量 $w3sky 就不存在了。要写一个不会丢失本次计数值的计数函数,要将变量 $w3sky 定义为静态(static)的:
如下:
复制代码 代码如下:

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

本函数每调用Test()都会输出 $w3sky 的值并加一。
静态变量也提供了一种处理递归函数的方法。递归函数是一种自己调用自己的方法。写递归函数时要小心,因为可能会无穷递归下去,没有出口.务必确保 有方法来中止递归。以下这个简单的函数递归计数到 10,使用静态变量 $count 来判断何时停止:
静态变量与递归函数的例子:
复制代码 代码如下:

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

注: 静态变量可以按照上面的例子声明。如果在声明中用表达式的结果对其赋值会导致解析错误。
声明静态变量例子:
复制代码 代码如下:

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;
}
?>
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