Page 1 of 1

Retrieve Singleton object from session

Posted: Thu Jun 21, 2007 7:49 pm
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)

Posted: Thu Jun 21, 2007 7:53 pm
by feyd
Should is not be protected instead of public?

Posted: Thu Jun 21, 2007 8:09 pm
by superdezign
If it was protected, how would I get the object from the session into it?

Posted: Thu Jun 21, 2007 8:25 pm
by feyd
PHP should likely handle that already.

Posted: Thu Jun 21, 2007 8:27 pm
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);

Posted: Thu Jun 21, 2007 9:58 pm
by superdezign
Thanks for that. :D
I was so into coding, I forgot to thank you.