Retrieve Singleton object from session

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Retrieve Singleton object from session

Post by superdezign »

I've tried out this Singleton pattern for a few objects and it helps me with dealing with references versus copies that may occur (from not paying attention). However, I have an object (user login object) that I save to the session, and would like to retrieve. I created a SetInstance() function in order to allow this is be transportable, but I've run into a problem with the __CLASS__ magic constant.

Code: Select all

public function SetInstance($instance)
{
	if(!$instance instanceof __CLASS__)
	{
		return;
	}
	
	self::$instance			= $instance;
}

Code: Select all

Parse error: syntax error, unexpected T_CLASS_C, expecting T_STRING or T_VARIABLE
Am I using __CLASS__ incorrectly? (I must be if I'm getting the error :P)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Should is not be protected instead of public?
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

If it was protected, how would I get the object from the session into it?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

PHP should likely handle that already.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

instanceof accepts 'string' (T_STRING), $var, $obj->property and alike (dynamic_class_name_reference) on the right side. But not __CLASS__ (T_CLASS_C). If you pass a variable of the type string it uses the value as a classname.

Code: Select all

<?php
class Foo {
	protected static $instance = null;
	
	public static function SetInstance($instance)
	{
		$a = __CLASS__;
		if( !$instance instanceof $a )
		{
			echo 'rejecting ', get_class($instance), "\n";
			return;
		}

		self::$instance = $instance;
		echo 'Ok';
	}
}

$f1 = new stdClass;
Foo::SetInstance($f1);

$f2 = new Foo;
Foo::SetInstance($f2);
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

Thanks for that. :D
I was so into coding, I forgot to thank you.
Post Reply