Re: Problems with singletons

From: Date: Mon, 21 Apr 2003 02:52:19 +0000
Subject: Re: Problems with singletons
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-144591@lists.php.net to get a copy of this message
Instead, maybe try something like: function &singleton() { static $instance = NULL; if(is_null($instance)) $instance = &new TestClass(); return $instance; } --- Seairth Jacobs seairth@seairth.com "Alan McFarlane" <mcfarlane_alan@lycos.co.uk> wrote in message news:20030420133035.94412.qmail@pb1.pair.com... > I'm having a strange problem with creating singletons. Specifically, I need > to be able to access one and only one instance of a class within my code, > but the following test code fails. > > The results (listed after the example) show that $instance_1 and $instance_2 > are in fact different instances of the TestClass. > > I would have though that they would be the same or am I making a fundamentel > error somewhere...? > > > [CODE] > <?php > > class TestClass > { > var $_signature = null; > > function &singleton( ) > { > static $instance; > > if (!isset($instance)) > $instance = &new TestClass(); > > return $instance; > } > > function TestClass( ) > { > $this->_signature = sha1(microtime()); > } > > function signature( ) > { > return $this->_signature; > } > } > > echo "<pre>"; > > // create an instance of TestClass > $instance_1 = &TestClass::singleton(); > echo "instance_1-&gt;signature() = " . $instance_1->signature() . > "<br>"; > > // short delay > sleep(1); > > // create another instance of TestClass > // this SHOULD be the smae as instance_1 > $instance_2 = &TestClass::singleton(); > echo "instance_2-&gt;signature() = " . $instance_2->signature() . > "<br>"; > > echo "\n"; > > // just to show that instance_1 and instance_2 STILL are different > echo "instance_1-&gt;signature() = " . $instance_1->signature() . > "<br>"; > echo "instance_2-&gt;signature() = " . $instance_2->signature() . > "<br>"; > > echo "</pre>"; > > ?> > [/CODE] > > Results: > > instance_1->signature() = d8f9adee7e5e0de91e09572264faeb4aff60d4e1 > instance_2->signature() = bdd0021aa84c0fd215b1b43158285e38dd55d90d > > instance_1->signature() = d8f9adee7e5e0de91e09572264faeb4aff60d4e1 > instance_2->signature() = bdd0021aa84c0fd215b1b43158285e38dd55d90d > > >

« previous php.general (#144591) next »