2

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

2
  • 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.
    – sberry
    Aug 27, 2011 at 20:28
  • Thanks for the reply and everyone for the help
    – morleyc
    Aug 28, 2011 at 5:05

4 Answers 4

2

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.

1

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

1

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.

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.