Passing data in PHP Singleton between hook calls

I created a simple Drupal module that uses a singleton simulation template to store data between call calls. However, this does not seem to be data storage, as I hope.

It's also a problem understanding PHP, not Drupal, but in case anyone has Drupal advice, here's what I do.

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 problem is visible 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(); } 

Error message

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

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

Can anyone understand what is wrong?

+4
source share
3 answers

This is not C ++:

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

Must be:

 public function getFileName() { return $this->_fileName; } public function setFileName($fileName) { $this->_fileName = $fileName; } 
+5
source

You must specify your field with the keyword $this :

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

And in the customizer too, of course:

 public function setFileName($fileName) { $this->_fileName = $fileName; } 
+2
source

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

+1
source

All Articles