El miembro estático de PHP no tiene valor

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.

¿Alguna idea?

Gracias por adelantado,

Chris

preguntado el 27 de agosto de 11 a las 20:08

That is right. The static members' state is not persistent between different webserver requests. You need to do this in another way if you want that behavior. Database, caching, sessions, cookies, etc, etc, etc. -

Thanks for the reply and everyone for the help -

4 Respuestas

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

Respondido 28 ago 11, 00:08

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

Respondido 28 ago 11, 00:08

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.

Respondido 28 ago 11, 00:08

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.

Respondido 28 ago 11, 00:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.