Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data in PHP Singleton between hook calls

Tags:

php

drupal-7

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?

like image 673
Kirk Avatar asked Feb 19 '23 02:02

Kirk


2 Answers

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; }
like image 182
Ja͢ck Avatar answered Mar 06 '23 10:03

Ja͢ck


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; }
like image 31
moonwave99 Avatar answered Mar 06 '23 08:03

moonwave99