drupal7中drupal_static函数源码分析-创新互联

我们在学习drupal7中,经常在看到函数中调用drupal_static()函数做静态缓存,提高函数的效率。在drupal_static()函数中,用到了PHP的static静态变量知识,这对于在同一个代码文件中,反复调用同一个函数,而函数的结果又可以做缓存处理时,是非常有用的。在drupal7中有如下两个函数:

创新互联公司主要从事网站设计、成都网站设计、网页设计、企业做网站、公司建网站等业务。立足成都服务伊犁,十年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:13518219792
  1. drupal_static($name,$default_value = NULL,$reset = FALSE);

  2. drupal_static_reset($name = NULL);

drupal7的API代码如下:

https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal_static/7.x

function &drupal_static( $name,$default_value = NULL,$reset = FALSE ){     static $data = array(),$default = array(); //First check if dealing with a previously define static varibale if( isset( $data[$name] ) || array_key_exists($name,$data) ){     //不为空 $name $data[$name] $default[$name] 静态变量也存在 if( $reset ){     $data[$name] = $default[$name]; } return $data[$name]; } //$data[$name] 或者 $default[$name] 都不存在静态变量中 if( isset( $name ) ){     if( $reset ){     //在默认设置之前调用重置 而且必须返回一个变量 return $data; } $default[$name] = $data[$name] = $default_value; return $data[$name]; }     //当$name == NULL 重置所有 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_reset()的参考代码 function drupal_static_reset( $name = NULL ){     drupal_static($name,NULL,TRUE); }

针对上面两个函数,测试代码如下:

  1. 可做静态缓存案例

function test1(){ $result = false;      $result = &drupal_static(__FUNCTION__);  if( !$result ){      error_log( 'test1test1test1test1test1' );  $result = 'get test1';  }  return $result; } $a = test1(); echo $a;//get test1 输出error_log日志 $b = test1(); echo $b;//get test1 但不会有error_log日志

2. 可恢复静态变量初始值测试

function test1(){ static $result = 1; $result = &drupal_static(__FUNCTION__,1);  echo $result;  $result++; } $a = test1(); echo $a;//1 $b = test1(); echo $b;//2 drupal_static_reset('test1');//此处将静态变量又重置为初始值 $c = test1(); echo $c;//1

以上代码仅供参考,具体使用请参看drupal7官方文档

另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


文章标题:drupal7中drupal_static函数源码分析-创新互联
文章地址:http://myzitong.com/article/pdpis.html