2

I saw something I didn't completely understand in the drupal CAS module, line 245 of cas.module:

  $initialized = &drupal_static(__FUNCTION__, FALSE);

What is going on with the function having the reference symbol before it? I thought it could only work with variables. Can someone give me a simple explanation of this? What happens when a function is called thusly, and what is the value of $initialized?

Sander Toonen
  • 3,463
  • 35
  • 54
user151841
  • 17,377
  • 29
  • 109
  • 171
  • see here http://stackoverflow.com/questions/4355300/difference-between-function-and-function and here http://php.net/manual/en/language.references.return.php – Pwner Jan 13 '15 at 15:58

2 Answers2

1

The return from the function is returned as a reference. From the manual:

Returning by reference is useful when you want to use a function to find to which variable a reference should be bound. Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own.

nickb
  • 59,313
  • 13
  • 108
  • 143
1

Drupal uses the function to cache data during a single page load. It can actually be used in the same way as:

static $initialized = false;

Only, by using a central store and keeping a record of the variables by function name, other functions are able to access, (and even more important for Drupal, reset) the value during a page request.

How Drupal uses it:

Jeff Eaton created a nice blog post about drupal_static and other caching techniques in Drupal 7.

Say another module wants to call your function, since you have set $initialized to true you know you can fetch the data from the cache. But what if that other module doesn't want you to cache it? It can then reset your static variable as follows:

$initialized = &drupal_static('your_module_your_function');
$initialized = false;

$freshData = your_module_your_function();

It might not be the cleanest pattern, but this is how Drupal does it in many places.

What it does from a PHP point of view :

using this construct allows the called function to return its value by-reference instead of by-value. In order to do so the called function has to be defined with an ampersand as well, e.g.:

public function &getBar() {
    return $this->bar;
}

You can even combine it with parameters by-reference. That way you can pass a reference all the way trough a function such that when you alter the returned value, you alter the original value as well. For example:

function &getRef(&$x) {
    return $x;
}

$a = 1;
$b = &getRef($a);
$b++;

echo $a; // Will output 2
Sander Toonen
  • 3,463
  • 35
  • 54