RE: global class instance

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



>> hi all,
>> i wonder if there is a way of creating an instance of a class and
>> reach it direcly from any scope in PHP4. basically what i want is:

>> i don't want to:
>>    - declare global $foo,
>>    - use pre-defined $GLOBALS variable,
>>    - or use a::print
>>
>> thanks.

> Static is your friend.

>
http://www.horde.org/papers/kongress2002-design_patterns/11_singleton_impl.x
ml.html

Also, if using PHP 4, make sure to read the "References with global and
static variables" section. It doesn't work quite the way a lot of people
expect it to.

http://us2.php.net/static

The manual isn't all that clear, but the user comments help a lot (which, I
have found, is often the case, but that's a rant for another day... At least
we have a manual that accepts such comments!)

class Singleton {
	function &getFoo() {
		$object =& Singleton::getFooRef();
		if (!is_a('Foo', $object)) {
			$object =& new Foo();
		}
		return $object;
	}

	function &getFooRef() {
		static $object = null;
		return $object;
	}
}

$myFoo =& Singleton::getFoo();

Hope that helps.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux