4

I've created a simple Drupal module which is using a singleton design pattern to preserve data between hook calls. However, this doesn't appear to be saving the data as I'd hope.

Also this seems to be a PHP understanding problem and not Drupal, but in case someone has a Drupal tip, here is what I'm doing.

The singleton setup

class TempStore {
  private $_fileName;
  public function getFileName() { return $_fileName; }
  public function setFileName($fileName) { $_fileName = $fileName; }

  function __construct() {

  }
}

function MYMODULE_data() {
  static $data;

  if (!isset($data))
    $data = new TempStore();

  return $data;
}

The trouble is seen even within the same function.

function MYMODULE_file_insert($file) {
  $token = $file->timestamp;
  MYMODULE_data()->setFileName($token);

  // error message: Notice: Undefined variable: _fileName in TempStore->getFileName()  
  $checkVal = MYMODULE_data()->getFileName();
}

The error message is

Notice: Undefined variable: _fileName in TempStore->getFileName()

Since this happens in the same function call, I believe this is a failure in my understanding of how PHP handles this sort of thing and not really related to Drupal.

Can someone see what is wrong?

Kirk
  • 16,182
  • 20
  • 80
  • 112

3 Answers3

5

This is not C++:

public function getFileName() { return $_fileName; }
public function setFileName($fileName) { $_fileName = $fileName; }

Should be:

public function getFileName() { return $this->_fileName; }
public function setFileName($fileName) { $this->_fileName = $fileName; }
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
2

You should refer to your field with $this keyword:

 public function getFileName() { return $this->_fileName; }

And in the setter as well of course:

public function setFileName($fileName) { $this->_fileName = $fileName; }
apaderno
  • 28,547
  • 16
  • 75
  • 90
moonwave99
  • 21,957
  • 3
  • 43
  • 64
1

You need to access $_fileName with $this->_fileName. Unrelated to your question but you should declare your static $data object as private static $data in the class that method is used in, outside of the function - then refer to that variable as self::$data when you test it, set it, and return it.

anjunatl
  • 1,027
  • 2
  • 11
  • 24