Jump to content

Singleton Pattern


killboy

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.
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.

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

You can save the object in the session if you want, as long as doesn't have any properties that are unserializable. You can't serialize a database connection, for example, or a file handle, but you can serialize other objects and arrays and scalar values.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...