[nycphp-talk] How to create a singleton class in PHP
Phil Powell
phillip.powell at adnet-sys.com
Fri Feb 13 10:31:07 EST 2004
Dan, one final happy footnote:
I was successfully able to convert my ActionHandler class into PHP4's
closest thing to a Singleton Design Pattern:
class ActionHandler {
// UNCOMMENT THIS LINE IN PHP 5
// static $instance =& new ActionHandler();
function &ActionHandler() {}
function &getActionHandler() {
static $instance;
if (!isset($instance)) $instance =& new ActionHandler();
return $instance;
}
function &getErrorArray() {
return ActionHandler::setErrorArray();
}
function &setErrorArray($additionalErrorArray) {
static $errorArray;
if (is_array($additionalErrorArray)) $errorArray +=
$additionalErrorArray;
return $errorArray; // THROWS ARRAY BUT IS CAUGHT BY getErrorArray()
}
}
And then in my main script, index.php, I simply do this:
$ah =& ActionHandler::getActionHandler();
// BLAH BLAH BLAH
$ah = null;
And then with all of my classes I use the "static" type class notations
to use the class:
if (somethingBreaks) ActionHandler::setErrorArray(array('action' =>
'Oops you goofed'));
Tested it out and everything works perfectly! Thanx for your help
Phil
Dan Cech wrote:
> No problem.
>
> In PHP5 you could just implement it a little differently with
> $errorArray being a static class variable instead of a static variable
> inside the function.
>
> However, if you wanted to be able to have classes inherit from the
> ActionHandler class and be able to call the functions as object
> methods on instances of those classes, or instances of the
> ActionHandler class, the implementation we ended up with is the only
> way to go.
>
> Dan
>
> Phil Powell wrote:
>
>> Forcing the keys to be unique fixed the problem and no need to use
>> $GLOBALS. But honestly, this will [probably] be easier in PHP5.
>>
>> Thanx for your patience.
>>
>> Phil
>
>
> _______________________________________________
> talk mailing list
> talk at lists.nyphp.org
> http://lists.nyphp.org/mailman/listinfo/talk
>
--
Phil Powell
Web Developer
ADNET Systems, Inc.
11260 Roger Bacon Drive, Suite 403
Reston, VA 20190-5203
Phone: (703) 709-7218 x107 Cell: (571) 437-4430 FAX: (703) 709-7219
EMail: Phillip.Powell at adnet-sys.com AOL IM: SOA Dude
More information about the talk
mailing list