3

I am trying to store file information to be passed around in the backend, so I created a singleton class with a static array and static methods accessing the array.

However when it comes to retrieving the data, I just get an empty array. Where am I going wrong here?

class FileStore {

private static $_tempFileData = array();
private static $initialized = false;

private function __construct() {}

private static function initialize() {
    if (self::$initialized)
        return;
    self::$initialized = true;
}

public static function storeTempFileData($data) {
    self::initialize();
    self::$_tempFileData[] = $data;
}

public static function getTempFileData() {
    self::initialize();
    return self::$_tempFileData;
}

public static function clearTempFileData() {
    self::initialize();
    unset(self::$_tempFileData);
}
}
user1724416
  • 914
  • 2
  • 11
  • 24
  • 1
    Can you paste code where you store array and get it? – vanadium23 Apr 27 '15 at 14:48
  • Singleton looks werid [Creating the Singleton design pattern in PHP5](http://stackoverflow.com/questions/203336/creating-the-singleton-design-pattern-in-php5) – cske Apr 27 '15 at 14:51

1 Answers1

2

First of all, this is not a singleton, but a static class. Singleton assumes creating an instance of class.

In your code I see that storeTempFileData appends a value to static variable, but getTempFileData doesn't return the same value - it returns an array.

One more problem - after you unset self::$_tempFileData, it's not an array anymore. So self::$_tempFileData[] = $data; will trigger a notice.

Basically I think you need to change self::$_tempFileData[] = $data; to self::$_tempFileData = $data;.

astax
  • 1,769
  • 1
  • 14
  • 23
  • correct after the first clear it won't work any more – cske Apr 27 '15 at 14:53
  • Ok so if I wanted to just access that static array, add elements and retrieve the array, how would this be possible? – user1724416 Apr 27 '15 at 15:07
  • So you indeed wanted it to return an array rather than what you're setting in `storeTempFileData`? Ok, in this case, change `unset(self::$_tempFileData);` to `self::$_tempFileData) = array()`. Apart from this, the code seems to be correct. Please provide example code where you use this class and it doesn't work as expected. – astax Apr 27 '15 at 16:08