在PHP中,我怎样才能确保在调用函数时函数中声明的静态变量不会重新启动?

Ode*_*ded 3 php static

似乎在调用函数时重新启动函数中声明的静态变量,如何以重新调用函数的方式使用该函数将重用静态参数?

我在static.php中定义了函数'testStatic'

这是static.php:

<?php
function testStatic()
{
    static $staticV = 0;
    echo $staticV;
    $staticV;
}
?>
Run Code Online (Sandbox Code Playgroud)

我从index.php调用'testStatic'

这是index.php:

<?php include "./static.php";?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"   "http://www.w3c.org/TR/html4/strict.dtd">
<?php
testStatic();
?>

<html> 
.
.
.
<html>
Run Code Online (Sandbox Code Playgroud)

当index.php第一次执行时,testStatic将以'0'回显,但是在下一次执行index.php时,testStatic继续以'0'回显.似乎每当执行index.php时,都会重新启动'testStatic'的静态变量'staticV'.

请指教.index.php

zom*_*bat 7

每次执行PHP脚本时,都会重新创建环境.HTTP请求或脚本调用之间没有状态.

第一次指向Web浏览器时index.php,将初始化新的PHP环境,并将其设置为$staticV0.

下次您将Web浏览器指向时index.php,会发生完全相同的事情.

如果要$staticV在Web请求之间保持持久性,则需要采用不同的方法. 会话通常用于处理此问题.