NYCPHP Meetup

NYPHP.org

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

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


Hmm, that is very similar to the GLOBALS kludge I posted, although it 
doesn't work on my machine.  Each subsequent call to setErrorArray is 
overwriting the error array.

Thus far the best I've got is:

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

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

     if ( is_array ($additionalErrorArray) ) {
       $errorArray += $additionalErrorArray;
     }

     return $errorArray;
   }
}

and for the $GLOBALS kludge:

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

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

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

     return $GLOBALS['errorArray'];
   }
}

Both of those functions work 100% for anything I've thrown at them.

Dan

Phil Powell wrote:
> I found a rather tragic kluge to get my code working again:
> 
> class ActionHandler {
> 
> function &ActionHandler() {
>  static $errorArray = array();
> }
> 
> function &getErrorArray() {
>  return $GLOBALS[$errorArray];
> }
> 
> function &setErrorArray($additionalErrorArray) {
>  if (is_array($additionalErrorArray)) $this->errorArray =& 
> array_merge($this->errorArray, $additionalErrorArray);
>  if (!isset($GLOBALS[$errorArray])) $GLOBALS[$errorArray] = 
> $this->errorArray;
> }
> 
> }
> 
> That produces the results I want every time, and I can't understand why 
> I must use $GLOBALS[$errorArray] and not $GLOBALS['errorArray'], am I 
> not mistaken that arrays can only take scalar string and/or integer 
> values as keys?
> 
> Phil





More information about the talk mailing list