Re: Singleton Pattern?

From: Date: Thu, 18 Mar 2004 22:34:59 +0000
Subject: Re: Singleton Pattern?
References: 1  Groups: php.pear.dev 
Request: Send a blank email to pear-dev+get-26568@lists.php.net to get a copy of this message
Paul M Jones wrote:
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.
maybe? return &$obj; -- paperCrane <Justin Patrin>

« previous php.pear.dev (#26568) next »