我正在使用Drupal,在我的.module文件中,我有两个函数,它们被称为来自hook_block_view的'content',如下所示:
function modulename_block_view($block_name = '')
{
$block = array();
global $form_st;
switch($block_name){
case 'first':
$block['subject'] = t("files from ".$_SESSION['form_state1']['values']['appName']);
$block['content'] = first_block_contents($block_name) ;
return $block;
break;
case 'second':
$block['subject'] = t("page view");
$block['content'] = second_block_contents($block_name);
return $block;
break;
}
所以在'first_block_contents()'函数中,定义了一个对象。我需要具有相同信息的相同对象,以便在'second_block_contents()'函数中可访问。类似的问题有很多答案,但我找不到这种特殊的问题。
答案 0 :(得分:1)
如果是在同一个请求中,您可以声明一个静态变量。 Drupal 7多次使用它。检查drupal_static
功能的documentation。
static $drupal_static_fast;
if (!isset($drupal_static_fast)) {
$drupal_static_fast ['whatever'] = &drupal_static(__FUNCTION__);
}
$whatever = &$drupal_static_fast ['whatever'];
switch($block_name){
case 'first':
$block['subject'] = t("files from ".$_SESSION['form_state1']['values']['appName']);
$block['content'] = first_block_contents($block_name) ;
// Set the static variable contents
$whatever = "Your Value";
return $block;
break;
case 'second':
// Use the $whatever variable now
$block['subject'] = t("page view");
$block['content'] = second_block_contents($block_name);
return $block;
break;
}
答案 1 :(得分:0)
为了在函数内部可访问,必须将变量声明为全局变量。例如:
function first_block_contents() {
global $aGlobalObject;
$aGlobalObject = new StdClass();
$aGlobalObject->val = 1;
}
function second_block_contents() {
global $aGlobalObject;
echo aGlobalObject->val; // will print "1"
}
请注意,必须在first_block_contents()
之前调用函数second_block_contents()
才能初始化变量。