[nycphp-talk] Articles/Code i have Written
Dan Cech
dcech at phpwerx.net
Wed Sep 22 09:22:07 EDT 2004
Joseph Crawford wrote:
> also i would like to note that i havent really found a use for that
> singleton pattern shown before in php 4, rather here is another code
> example i posted that will show a better way to use a method to get
> similar results.
>
> http://www.weberdev.com/get_example-4014.html
You may be better off with something like this:
function &singleton($class) {
static $instances;
if (!is_array($instances)) {
$instances = array();
}
if (!isset($instances[$class])) {
$instances[$class] =& new $class;
}
return $instances[$class];
}
This function will correctly manage multiple singleton objects for
multiple classes, thus:
$mysingle =& singleton('myclass');
$myother =& singleton('anotherclass');
Will both be valid singleton instances of their respective class. With
the function in your example the second call to singleton would change
the object referenced by $mysingle.
I also changed the way the function returns the reference slightly to
reflect the preferred syntax in php4.
Dan
More information about the talk
mailing list