tags:

views:

131

answers:

5

Hi,

In ASP.NET if I declare a variable (or object) static (or if I make a singleton) I can have it persist across multiple sessions of multiple users (it it registered in a server scope) so that I don't have to initialize it at every request.

Is there such a feature in PHP? Thanks

A: 

You can do that with a PHP extension (written in C).

But if you want to write it in PHP, no. The best alternative is to write the variable to a file (file_put_contents()) at the end of each request, and open it at the start of each request (file_get_contents()).

That alternative isn't going to work for high volume sites because the processes will be doing read/write at the same time and the world will go all BLAAA-WOOO-EEE-WOHHH-BOOOM.

Coronatus
A: 

Sadly, no. PHP's static keyword is limited to the current script instance only.

To persist data across script instances for the same session, you would use the session handling features.

To persist data across sessions, you would have to use something like memcache, however that requires additional set-up work on server side.

Pekka
+1  A: 

you could store serialized copies of an object inside session

class test{
  private static $instance;
  public property;
  private __construct(){}
  public getInstace(){
    if(!self::$instance){
      self::$instance = new test;
    }
    return self::$instance;
  }
}

$p = test->getInstance();
$p->property = "Howdy";
$_SESSION["p"] = $p;

next page

$p = $_SESSION["p"];
echo $p->property; // "Howdy"
markcial
A: 

You can set up APC and use the apc_store and apc_fetch functions.

http://us.php.net/manual/en/book.apc.php

webbiedave
A: 

That doesn´t exist in PHP, however, you can serialize the data and put it either in a file on your hard drive or in /dev/shm/. You can also use memcache.

If you put your data in /dev/shm/ or use memcache the data will dissapear on reboot.

jwandborg