NYCPHP Meetup

NYPHP.org

[nycphp-talk] How to create a singleton class in PHP

Dan Cech dcech at phpwerx.net
Thu Feb 12 13:11:08 EST 2004


Hmm, I'm not sure exactly what you mean, could you try to post the 
minimum required code to demonstrate your problem?

Here is a slightly updated version of the code I posted before:

class ActionHandler {
   function &getErrorArray () {
     return ActionHandler::setErrorArray ();
   }

   function &setErrorArray ($additionalErrorArray = NULL) {
     static $errorArray = array();

     if ( is_array ($additionalErrorArray) ) {
       $errorArray = array_merge ($errorArray, $additionalErrorArray);
     }

     return $errorArray;
   }
}

You could also do this via a global variable:

class ActionHandler {
   function &getErrorArray () {
     return ActionHandler::setErrorArray ();
   }

   function &setErrorArray ($additionalErrorArray = NULL) {
     if ( !isset ($GLOBALS['errorArray']) ) {
       $GLOBALS['errorArray'] = array();
     }

     if ( is_array ($additionalErrorArray) ) {
       $GLOBALS['errorArray'] = array_merge ($GLOBALS['errorArray'], 
$additionalErrorArray);
     }

     return $GLOBALS['errorArray'];
   }
}

Dan

Phil Powell wrote:
> Sorry, Dan, that failed too.  It worked in FileGenerator class, but the 
> next class does a print_r(ActionHandler::getErrorArray()) and the array 
> value is null again.
> 
> Phil





More information about the talk mailing list