PHP static member not holding value

六月ゝ 毕业季﹏ 提交于 2021-02-16 20:59:09

问题


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

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.

The problem is the i value when calling via the ajax-response.php script is back to 0?

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.

Any ideas?

Thanks in advance,

Chris


回答1:


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.`

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.

If you want to persist stuff across multiple processes / requests in a web application, you need to use sessions.




回答2:


Ajax request is another request. That's why there are new variables
You may use session to store values between requests




回答3:


You might need sessions on this one. Variables are stored in the current instance only, so if you call another script and create an instance of the MyClass class all of its properties will be set to default.




回答4:


That's correct, you're variables won't stay active between different processes. Each process has it's own copy of the variable. You have many choices here.

You could use store the variable in a session if you want it to be short term storage. If you want to store it indefinitely you should store it in a database or a file.



来源:https://stackoverflow.com/questions/7217121/php-static-member-not-holding-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!