NYCPHP Meetup

NYPHP.org

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

Dan Cech dcech at phpwerx.net
Thu Feb 12 12:34:24 EST 2004


What you want is:

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

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

     if ( !is_array ($errorArray) ) {
       $errorArray = array();
     }

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

     return $errorArray;
   }
}

Dan

Phil Powell wrote:
> Actually I did just that..
> 
> class ActionHandler {
> 
>  function &ActionHandler($errorArray = '') {
>   if (!is_array($errorArray)) {
>    static $errorArray = array();
>   } else {
>    $this->errorArray =& $errorArray;
>   }
>  }
> 
>  function &getErrorArray() {
>   static $instance;
>   if (!isset($instance)) {
>    $instance =& new ActionHandler($this->errorArray);
>    $instance->setErrorArray($this->errorArray);
>    return $instance->errorArray;
>   }
>   return $this->errorArray;
>  }
> 
>  function &setErrorArray($additionalErrorArray) {
>   if (is_array($additionalErrorArray)) array_merge($this->errorArray, 
> $additionalErrorArray);
>  }
> 
> }
> 
> This construct did not give me the results i wanted, for example, in the 
> class FileGenerator, it does stuff and if something fails:
> 
> ActionHandler::setErrorArray(array('action' => 'Something broke'));
> 
> Which is fine.. I do a print_r(ActionHandler::getErrorArray()) from the 
> FileHandler class object and this is what I see:
> 
> Array (action => Something broke)
> 
> HOWEVER... if I then go to ANOTHER class and IMMEDIATELY AFTER I have 
> done my setErrorArray() from FileHandler class I do this:
> 
> print_r(ActionHandler::getErrorArray())
> 
> I see this
> 
> Array ()
> 
> FileHandler class succssfully sets the what-should-be-single-instance 
> array $errorArray, but then the next class after it sees nothing in 
> $errorArray.
> 
> The construct I want to create is what is in Java the singleton class: i 
> want only ONE instance of ActionHandler to persist.. every single class 
> can then add to the one single-instance array $errorArray whatever it 
> wants and $errorArray will retain everything it gets.
> 
> Phil





More information about the talk mailing list