Do you have a question? Post it now! No Registration Necessary. Now with pictures!
- Posted on
- PHP static scope
January 23, 2006, 7:23 pm
rate this thread
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()
self::$instance = new MyClass();
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
I'm just messing with things on IIS - incase that could be the issue.
Re: PHP static scope
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
Re: PHP static scope
I'm coming from an ASP.NET background where the use of static is more
traditional (or atleast, independent of web paradigms). In ASP.NET it
can obviously lead to considerably thread-safety issues if improperly
I'll simply design my solution differently :)
Thanks for the help,