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

十载的曲水网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。成都全网营销推广的优势是能够根据用户设备显示端的尺寸不同,自动调整曲水建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。成都创新互联从事“曲水网站设计”,“曲水网站推广”以来,每个客户项目都认真落实执行。
drupal_static($name,$default_value = NULL,$reset = FALSE);
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);
}针对上面两个函数,测试代码如下:
可做静态缓存案例
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官方文档
分享文章:drupal7中drupal_static函数源码分析
网页URL:http://www.jxjierui.cn/article/igdidp.html


咨询
建站咨询
