Problems with singletons
| From: | Alan McFarlane | Date: | Sun, 20 Apr 2003 13:30:04 +0000 |
| Subject: | Problems with singletons | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-144537@lists.php.net to get a copy of this message | ||
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->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->signature() = " . $instance_2->signature() .
"<br>";
echo "\n";
// just to show that instance_1 and instance_2 STILL are different
echo "instance_1->signature() = " . $instance_1->signature() .
"<br>";
echo "instance_2->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