PHP 静态成员不保值 [英] PHP static member not holding value
问题描述
我正在编写的 WordPress 插件有一个奇怪的问题,但这与 WordPress 本身无关,更多与 PHP 相关,所以请继续阅读,以便我解释.连接了 WordPress 插件,以便调用 init() 函数......这有效,我可以确认它被调用一次.
Hi i have a strange problem with a WordPress plugin that i am writing, but this isnt about WordPress per se and more to do with PHP so please read on so I can explain. The WordPress plugin is hooked up so that the init() function gets called... this works i can confirm it gets called once.
class MyClass
{
static $i=0;
public static function init()
{
self::$i++;
}
public static function dosomething()
{
echo 'i is = ' . self::$i;
}
}
当第一次从 Wordpress 中调用 inf dosomething() 时是可以的.然后我有另一个 ajax-response.php 文件,其中包含上述类并再次调用 dosomething,它打印 i 值 = 1.
When callinf dosomething() for the first time from within Wordpress it is ok. I then have another ajax-response.php file which includes the above class and again calls dosomething, which prints the i value = 1.
问题是通过ajax-response.php脚本调用时i值回0了吗?
The problem is the i value when calling via the ajax-response.php script is back to 0?
就好像它在一个完全不同的内存空间中执行并创建一个新程序,这样静态成员变量只在同一个进程之间共享,而不是在多个 Web 线程之间共享.
Its as if it is executing in a totally different memory space and creating a new program, such that static member variables are only shared between same process as opposed to multiple web threads.
有什么想法吗?
提前致谢,
克里斯
推荐答案
就好像它在一个完全不同的内存空间中执行并创建一个新程序,这样静态成员变量只在同一个进程之间共享,而不是在多个 Web 线程之间共享.`
Its as if it is executing in a totally different memory space and creating a new program, such that static member variables are only shared between same process as opposed to multiple web threads.`
没错!:) 这是 100% 的工作原理.每个 PHP 请求都是一个新的请求,有自己的内存.static
关键字不是用来解决这个问题的.
Exactly! :) That's 100% how this works. Each PHP request is a new one, with its own memory. The static
keyword is not designed to work around that.
如果你想在一个 web 应用程序中跨多个进程/请求持久化东西,你需要使用 会话.
If you want to persist stuff across multiple processes / requests in a web application, you need to use sessions.
这篇关于PHP 静态成员不保值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!