温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

drupal7 中drupal_static函数源码分析

发布时间:2020-07-22 04:13:18 来源:网络 阅读:675 作者:ADUJ 栏目:web开发

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

  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官方文档

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI