Retrieving data from a PHP singleton class

I am trying to store information about files that will be transferred to the backend, so I created a singleton class with a static array and static methods that access the array.

However, when it comes to getting data, I just get an empty array. Where am I 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);
}
}

      

+3


source to share


1 answer


First of all, it is not a single class, but a static class. Singleton involves creating an instance of a class.

In your code, I can see that it is storeTempFileData

adding a value to a static variable, but getTempFileData

not returning the same value - returning an array.



Another problem is after you undo self::$_tempFileData

it is no longer an array. Thus, self::$_tempFileData[] = $data;

will trigger a notification.

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

to self::$_tempFileData = $data;

.

+2


source







All Articles