Re: new overloading feature?
| From: | Andrey Hristov | Date: | Fri, 05 Nov 2004 16:28:06 +0000 |
| Subject: | Re: new overloading feature? | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-13732@lists.php.net to get a copy of this message | ||
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? <?php 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 */?>