globals in Drupal modules
Submitted by ivan on Tue, 10/02/2007 - 20:06.
inside the module, where somehook() was a callback function; but if I called test() in the module body and not inside a function or if I call the same snippet of code but outside drupal module everything was working.
or
Why globals aren't globals in drupal modules
I was writing a module for Drupal. I needed to connect to another DB (MS SQL) and I had my classes and some legacy code I'd like to push into the module.
I was getting something like this:
Fatal error: Call to a member function test() on a non-object in ...
when I wrote something like:
<?
php
class tonno {
protected $pippo=null;
function __construct($pippo) {
$this->pippo=$pippo;
}
public function test() {
return $this->pippo;
}
}
$zoppas=new tonno("morto");
function somehook() {
global $zoppas;
return $zoppas->test();
}
?>inside the module, where somehook() was a callback function; but if I called test() in the module body and not inside a function or if I call the same snippet of code but outside drupal module everything was working.
Thanks to the people at #drupal I learned that modules are in the namespace of drupal_load and while functions and classes are globally available, instance of class and variables declared in a function are not (uh!).
Possible solution could be:
<?
php
$['GLOBALS']['zoppas'] = new tonno();
global $zoppas=new tonno();
?>or
<?
php
function getzoppas() {
static $zoppas;
if (!isset($zoppas)) {
$zoppas = new tonno();
}
return $zoppas;
}
function somehook() {
$zoppas=getzoppas();
}
?>Many thanks to Crell, eaton and merlinofchaos