search
Homephp教程php手册php中static静态变量的使用方法详解

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

Jun 13, 2016 pm 12:15 PM
phpstaticcodeInstructionsvariablecopyExampleoflookDetailed explanationstatic

看看下面的实例:

复制代码 代码如下:


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.