Re: do pear packages create their own seperate DB connections?

From: Date: Tue, 22 Apr 2003 20:34:14 +0000
Subject: Re: do pear packages create their own seperate DB connections?
References: 1 2 3 4 5 6 7  Groups: php.pear.dev 
Request: Send a blank email to pear-dev+get-15352@lists.php.net to get a copy of this message
Jon Wood wrote:
class x {
    function &getInstance()
    {
        $varName = '__'.__CLASS__;
        if (!isset($GLOBALS[$varName]) ||
            get_class($GLOBALS[$varName])!=__CLASS__) {
            $GLOBALS[$varName] =& new x();
        }
        return $GLOBALS[$varName];
    }
} this way it gets saved in the global namespace, i know. its not really cool. but may be someone knows a better and nicer way or is it even simpler with php4?
Is there a problem with statics? That's a serious question... I thought from reading the docs they're in v4, but I'm not certain. Jon Statics are a much better way to handle this IMO. There is some fringe behavior with statics in singleton method, however. (At least when using PHP4 which doesn't have class-scope static variables).
I generally use: function &getInstance() { static $instance; if (!isset($instance)) {
      $instance = new Class(); // NOT by reference
} return $instance; } The catch is that you cannot assign static vars by reference. That means that you cannot do $instance = &new Class(). Usually this is fine, sure it's making a copy originally, but every time you call Class::getInstance() you are receiving that same copy (i.e. only one copy is ever made). Sometimes, however, making a copy of the class at instantiation returns a significantly different object. I believe that PEAR's Log class is an example of a class that should always be returned by reference (at least when using the factory() method), because in the construction of the class listeners are bound to _the_ instance of the class being constructed: $Log = &Log::factory('file', $params); // not the same as $Log = Log::factory('file', $params); (Not sure if that's a valid factory() signature, but it's just for example.) Cheers, Hans

Attachment: [application/x-pkcs7-signature] S/MIME Cryptographic Signature smime.p7s
« previous php.pear.dev (#15352) next »