NYCPHP Meetup

NYPHP.org

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

Phil Powell phillip.powell at adnet-sys.com
Thu Feb 12 12:21:53 EST 2004


jon baer wrote:

>i have not had to use it much but this is the function i have played around
>with when i first tried oo-php:
>
>function staticInstance($class) {
>    // Declare a static variable to hold the object instance
>    static $instance;
>
>    // If the instance is not there, create one
>    if(!isset($instance)) {
>        $instance =& new $class;
>    }
>    return($instance);
>}
>
>which i got from a good website:
>http://www.phppatterns.com/index.php/article/articleprint/6/-1/1/
>
>i think the lack of static variables makes it impossible - something php5
>will provide.
>
>- jon
>
>_______________________________________________
>talk mailing list
>talk at lists.nyphp.org
>http://lists.nyphp.org/mailman/listinfo/talk
>
>  
>

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

-- 
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