Re: Re: Singleton Pattern?
| From: | Paul M Jones | Date: | Fri, 19 Mar 2004 00:20:13 +0000 |
| Subject: | Re: Re: Singleton Pattern? | ||
| References: | 1 2 3 | Groups: | php.pear.dev |
| Request: | Send a blank email to pear-dev+get-26575@lists.php.net to get a copy of this message | ||
Hi, everyone,
First, thanks to everyone for the good responses; I'm sorry to trouble you guys with what appears now to be a commonly known issue. Sorry to take up time and bandwidth.
For the sake of posterity, the correct solution is for the static singleton() method to assign the object by copy, not by reference. This appears to be a known PHP4 bug; Stefan Neufeind wrote:
I've found the corresponding bug report: http://bugs.php.net/bug.php?id=12454 It says that "Static variables just can't hold references of any kind. For objects it's avoidable with ZE2 because of the new object model.". At that time it was marked as a documentation-problem, should have been fixed and is marked fixed in CVS (documentation). So the problem seems to be of technical nature and maybe isn't fixable with the "old" Zend-engine (php 4.x).The updated, properly working code looks like this: <?php class test {
var $val = 'default';
function &singleton()
{
static $obj;
if (! isset($obj)) {
echo "create ";
$obj = new test(); // **NOT** $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 a reference to the singleton)
$two =& test::singleton();
echo $two->get();
?>
Thanks again, everyone.
--
Paul M. Jones
pmjones@ciaweb.net
Savant: the simple alternative to Smarty.
http://phpsavant.com/