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 13:19:38 EST 2004


Dan Cech wrote:

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


That above code failed for me.  Say for instance you're in FileHandler 
class method getBackupFile():

if (!$fileID) ActionHandler::setErrorArray(array('action' => 'Backup 
file not found'));

Ok, right after this line, in the *very same method*, I do this for fun:

print_r(ActionHandler::getErrorArray());

I see

Array (action => Backup file not found)

OK?

Now I am out of the method and back in ActionPerformer::perform() method:

$fileGen =& new FileGenerator($db, $table);
$fileBackupContents = $fileGen->getBackupFile(); // THIS IS WHERE I SEE 
MY FIRST print_r() statement

..and have returned to my ActionPerformer::perform() method, the VERY 
NEXT LINE I do this:

print_r(ActionHandler::getErrorArray());

I see

Array ()

This happens if even I implement YOUR code into the mix.  Instead, were 
I to use $GLOBALS, everything works.  It's the PHP4 version of a 
"singleton" class w/o the singleton structure that I truly believe fails 
in PHP 4 at least 4.3.2 that I'm using at work.

Phil

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