Singleton Pattern?
| From: | Paul M Jones | Date: | Thu, 18 Mar 2004 22:30:10 +0000 |
| Subject: | Singleton Pattern? | ||
| Groups: | php.pear.dev | ||
| Request: | Send a blank email to pear-dev+get-26567@lists.php.net to get a copy of this message | ||
Hi everyone,
This is not strictly PEAR-related, but it is for a PEAR class I'm developing. If this is not the place, I'll ask elsewhere.
I am trying to implement a singleton pattern, but I am having the darnedest time. Have examined various examples (e.g., phppatterns.com, PEAR Log), but my own simple tests are failing.
The simple test code:
<?php
class test {
var $val = 'default';
function &singleton()
{
static $obj;
if (! isset($obj)) {
echo "create ";
$obj =& new test();
} else {
echo "reuse ";
}
return $obj;
}
function set($newval)
{
$this->val = $newval;
}
function get()
{
return $this->val;
}
}
// 1st instance
$one =& test::singleton();
$one->set('something ');
echo $one->get();
// 2nd instance (should be the same)
$two =& test::singleton();
echo $two->get();
?>
In theory, the output should be "create something reuse something" (i.e, $one gets a newly created test object, sets the value, and gets the value; $two should get a reference to the static test object and get the value from that same object).
However, the actual output is "create something reuse default" (i.e., $two is getting a new object, not the re-used reference to the static singleton).
Is there something obvious that I am doing wrong?
Thanks in advance for any help.
--
Paul M. Jones
Savant: the simple alternative to Smarty.
http://phpsavant.com/