RE: [PHP] global class instance

From: Date: Wed, 05 Jul 2006 20:32:39 +0000
Subject: RE: [PHP] global class instance
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-239151@lists.php.net to get a copy of this message
>> 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

« previous php.general (#239151) next »