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?
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; }
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With