导航

Drupal如何集中控制静态变量?

Posted on 2013-10-09 11:20  eastson  阅读(289)  评论(0编辑  收藏  举报

Drupal许多的函数中都使用了静态变量。按照通常的用法,静态变量的使用应该是这样的:

function drupal_set_title($title = NULL) {
  static $stored_title;

  if (isset($title)) {
    $stored_title = $title;
  }

  return $stored_title;
}

 

但是Drupal使用的方式有些不同。主要的考量应该是这样:可能会有几十上百个函数中使用了静态变量,Drupal需要在某一时刻对这些静态变量都做reset处理。这个时候,不可能对这几十上百个函数都重新调用一次。因此,Drupal需要一种机制,来集中地存放静态变量,这就是函数druap_static()存在的目的:

function &drupal_static($name, $default_value = NULL, $reset = FALSE) {
  static $data = array(), $default = array();
  
  // First check if dealing with a previously defined static variable.
  if (isset($data[$name]) || array_key_exists($name, $data)) {
    // Non-NULL $name and both $data[$name] and $default[$name] statics exist.
    if ($reset) {
      // Reset pre-existing static variable to its default value.
      $data[$name] = $default[$name];
    }
    return $data[$name];
  }
  
  // Neither $data[$name] nor $default[$name] static variables exist.
  if (isset($name)) {
    if ($reset) {
      // Reset was called before a default is set and yet a variable must be
      // returned.
      return $data;
    }
    
    // First call with new non-NULL $name. Initialize a new static variable.
    $default[$name] = $data[$name] = $default_value;
    return $data[$name];
  }
  
  // Reset all: ($name == NULL). This needs to be done one at a time so that
  // references returned by earlier invocations of drupal_static() also get
  // reset.
  foreach ($default as $name => $value) {
    $data[$name] = $value;
  }
  
  // As the function returns a reference, the return should always be a
  // variable.
  return $data;
}

注意,这里drupal_static()返回的是引用。

 

使用drupal_static()后的函数drupal_set_title()是这样的:

function drupal_set_title($title = NULL, $output = CHECK_PLAIN) {
  $stored_title = &drupal_static(__FUNCTION__);

  if (isset($title)) {
    $stored_title = $title;
  }

  return $stored_title;
}

 

当需要reset集中存储的静态变量时,可以调用函数drupal_static_reset():

function drupal_static_reset($name = NULL) {
  drupal_static($name, NULL, TRUE);
}