Newsgroups: php.internals Path: news.php.net Xref: news.php.net php.internals:13732 Return-Path: Mailing-List: contact internals-help@lists.php.net; run by ezmlm Delivered-To: mailing list internals@lists.php.net Received: (qmail 92937 invoked by uid 1010); 5 Nov 2004 16:31:24 -0000 Delivered-To: ezmlm-scan-internals@lists.php.net Delivered-To: ezmlm-internals@lists.php.net Received: (qmail 91363 invoked from network); 5 Nov 2004 16:30:57 -0000 Received: from unknown (HELO iko.gotobg.net) (80.168.8.116) by pb1.pair.com with SMTP; 5 Nov 2004 16:30:57 -0000 Received: from pd9519cba.dip.t-dialin.net ([217.81.156.186] helo=[192.168.0.36]) by iko.gotobg.net with esmtpa (Exim 4.43) id 1CQ6zM-0006jk-3r; Fri, 05 Nov 2004 18:31:00 +0200 Message-ID: <418BAA16.6020602@hristov.com> Date: Fri, 05 Nov 2004 17:28:06 +0100 User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8a5) Gecko/20041102 X-Accept-Language: en-us, en MIME-Version: 1.0 To: Derrell.Lipman@UnwiredUniverse.com CC: internals References: In-Reply-To: Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-AntiAbuse: This header was added to track abuse, please include it with any abuse report X-AntiAbuse: Primary Hostname - iko.gotobg.net X-AntiAbuse: Original Domain - lists.php.net X-AntiAbuse: Originator/Caller UID/GID - [47 12] / [47 12] X-AntiAbuse: Sender Address Domain - hristov.com X-Source: X-Source-Args: X-Source-Dir: Subject: Re: [PHP-DEV] new overloading feature? From: php@hristov.com (Andrey Hristov) Why not using Singleton for multiple objects with getInstance() ? Andrey Derrell.Lipman@UnwiredUniverse.com wrote: > I came across an interesting desire today. I'd like to create a new class > instance if an only if a "key" value does not already exist. This key value > could be looked up in a database, in an array, etc. > > The following contrived example shows use of a proposed __new() overload > function which would be called BEFORE the constructor, and could chose to > return a newly constructed object (by calling __construct()) or to return an > already existing object. > > One could certainly call a function which searched for the key value and only > instantiated a new object if the existing one was not found, but this seems > cleaner. > > Thoughts? > > > class X > { > static $allX = array(); > var $val; > > function __construct($val) > { > $this->val = $val; > X::$allX[] =& $this; > } > > function __new($val) > { > foreach (X::$allX as $x) > { > if ($x->val == $val) > { > return $x; > } > } > > return __construct($val); > } > } > > $try1 = new X(23); /* would return $allX[0] reference */ > $try2 = new X(42); /* woudl return $allX[1] reference */ > $try3 = new X(23); /* would return $allX[0] reference */ > ?> >