Jump to content

Singleton Pattern


killboy
 Share

Recommended Posts

Hi there.I am trying to make a singleton on PHP, but it doesn't work.As far as I know, a singleton is a class that can have only one instance.I am trying to call the class from another file, but it resets all its values. Is that it? I can't call the class from another file?Here's an example of what I mean:

class SingletonClass{	protected static $_instance = null;	protected function __construct()	{	}	static public function getInstance()	{		if ( self::$_instance === null )		{			self::$_instance = new self();			echo "instance";		}		return self::$_instance;	}}

index.php

include( "classes/SingletonClass.php" );$singleton = SingletonClass::getInstance();

anotherFile.php

include( "classes/SingletonClass.php" );$singleton = SingletonClass::getInstance();

Suppose I go to index.php and index.php redirects me to anotherFile. In both cases it echoes "instance". It should echo it just one, right?Anyone can help me?Thanks.

Link to comment
Share on other sites

Well, the instance only lasts until the script ends, and if you are really redirecting then the script will "end" when you change pages...

Link to comment
Share on other sites

I see... So, what should I do in order to keep the instance? Store it in an Session var?
AFAIK, you can't keep the instance. You can only keep the instance's scalar values as the session's data. You could still use a singleton to retrieve those values though, and if you must, you can reconstruct any non scalar values. Edited by boen_robot
Link to comment
Share on other sites

  • 3 weeks later...

Sorry I'm reviving this thread, but I prefer to ask this here rather than make a new topic.What's the point of doing a singleton on PHP? I mean, instance is not preserved through the different pages of a whole project.

Edited by killboy
Link to comment
Share on other sites

All instances of objects, in all languages, are destroyed upon exit. A singleton pattern is just an implementation detail of whatever class you have that indicates the class is supposed to be used in a certain way. For example, say you wrote a class that wrapped $_SESSION - you would perhaps implement that as a singleton, because there is only one session for the script.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...