drupal7 中drupal_static函數源碼分析

我們在學習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官方文檔

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章