|
Posted by ZeldorBlat on 01/23/06 22:22
ks wrote:
> Hello,
> I'm kinda new to PHP and I'm running into something that just seems
> odd. There's a good chance I'm just doing something wrong though. I'm
> trying to implement a simple singleton:
>
> private static $instance;
> public static function Instance()
> {
> if (!isset(self::$instance))
> {
> self::$instance = new MyClass();
> }
> return self::$instance;
> }
>
> which pretty much follows the common pattern. I've noticed through,
> either by using a var_dump on self::$instance or by simply outputting
> "test" inside the IF statement, that my if statement always executes.
> If I call Instance twice within the same request, the singleton works,
> but if I refresh or open a new browser, each request seems to create
> it's own version. Am I doing something wrong or are static's scoped to
> thread requests? I would expect the block within the if to fire once
> throughout the life of the application (or until php resets itself or
> whatever).
>
> I'm just messing with things on IIS - incase that could be the issue.
You're misunderstanding how this is supposed to work. Forget, for a
moment, about sessions, cookies, get and post. So, when the user
requests a page, PHP fires up, runs the PHP code and outputs HTML to
the browser. That script is done. No more. Not coming back.
Anything done on that page is "forgotten" before the next request.
Put another way, each request is independent. So, your observation
that "If I call Instance twice within the same request, the singleton
works" is correct, and is the expected behavior.
If you want things to persist between requests (or be shared among many
requests) you'll need to save that state somehow. This is the intended
use of sessions, cookies, get and post. If you want to share something
among many requests then you're looking at something like a database or
shared memory.
[Back to original message]
|