NYCPHP Meetup

NYPHP.org

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

Dan Cech dcech at phpwerx.net
Thu Feb 12 15:42:32 EST 2004


What version of PHP are you using Phil, also does the code I provided in 
my last email (below) work without modification?

The code you posted below is actually missing a few closing brackets, 
but other than that, adding a line to print details of 
$additionalErrorArray does not cause any issues for me.

Dan

Phil Powell wrote:
> Ran into a very weird problem now:
> 
> function &setErrorArray($additionalErrorArray) {
> static $errorArray = array();
> print_r("additionalErrorArray: "); print_r($additionalErrorArray); 
> print_r(" is array? "); print_r(sizeof($additionalErrorArray); 
> print_r("<P>");
> if (is_array($additionalErrorArray) $errorArray += $additionalErrorArray;
> return $errorArray;
> }
> 
> If I happen to actually be passing an array into setErrorArray here is 
> my output using:
> 
> ActionHandler::setErrorArray(array('willSelectFileArray' => 'Could not 
> locate backup file'));
> 
> Output:
> 
> additionalErrorArray: Array ( [willSelectFileArray] => Could not locate 
> backup file ) is array? 0
> 
> For some reason $additionalErrorArray lists as an array but has a 
> "sizeof" of 0.  If I use is_array() instead of sizeof() I get false.  In 
> short, the static method assumes the parameter is not an array, even 
> though it is, thus, the entire method fails to add any additional items 
> onto the static var $errorArray because it thinks everything it gets is 
> not an array, even though.. it is.
> 
> Phil
> 
> Dan Cech wrote:
> 
>> You shouldn't need the constructor, because the methods are only ever 
>> called as class methods, so it will never be executed.
>>
>> But you are absolutely correct about the fact that that there is only 
>> ever one instance of the $errorArray created within the setErrorArray 
>> function.
>>
>> Dan
>>
>> PS, if you wanted to be able to extend this class, you could use:
>>
>> class ActionHandler {
>>   function &getErrorArray() {
>>     return ActionHandler::_ErrorArray();
>>   }
>>
>>   function &setErrorArray($additionalErrorArray = null) {
>>     return ActionHandler::_ErrorArray($additionalErrorArray);
>>   }
>>
>>   function &_ErrorArray ($additionalErrorArray = null) {
>>     static $errorArray = array();
>>     if (is_array($additionalErrorArray)) {
>>       $errorArray += $additionalErrorArray;
>>     }
>>     return $errorArray;
>>   }
>> }
>>
>> You could then do:
>>
>> class myclass extends ActionHandler {
>> }
>>
>> $myobj = new myclass ();
>> $myobj->setErrorArray (array ('test' => 'test'));
>>
>> $myobj2 = new myclass ();
>> $myobj2->setErrorArray (array('hello' => 'tiger'));
>>
>> print_r (ActionHandler::getErrorArray ());





More information about the talk mailing list