php为什么基本的超级全球失败?

时间:2011-10-02 14:23:20

标签: php global-variables

我正在使用全局变量来共享像这样的函数之间的变量

<?php
$whatyear;
$whatfirstname;
$whatlastname;
function mycustom_user_register_submit($form, &$form_state)
{
            $GLOBALS["whatyear"]=$form_state['values']['yearofstudy'];
            $GLOBALS["whatfirstname"]=$form_state['values']['firstname'];
            $GLOBALS["whatlastname"]=$form_state['values']['lastname'];
}
function course_registration_user_insert(&$edit, $account, $category)
{
            $newuserid=$account->uid;
            $yearofstudy=$GLOBALS["whatyear"];
            $fname=$GLOBALS["whatfirstname"];
            $lname=$GLOBALS["whatlastname"];
                        //now use vars
                        drupal_set_message('dear '.$fname.' '.$lname.' ,'.'account uid is '.$account->uid); 
}

但变量

  

FNAME,L-NAME,yearofstudy

令人震惊的空洞!请帮我弄清楚原因。 我遇到了像

这样的错误
Notice: Undefined index: whatyear in course_registration_user_insert() (line 110 of C:\wamp\www\drupal-7.1\sites\all\modules\course_registration\course_registration.module).

1 个答案:

答案 0 :(得分:1)

尝试使用这样的全局变量:

<?php
function mycustom_user_register_submit($form, &$form_state)
{
    global $whatyear;
    global $whatfirstname;
    global $whatlastname;
    $whatyear=$form_state['values']['yearofstudy'];
    $whatfirstname=$form_state['values']['firstname'];
    $whatlastname=$form_state['values']['lastname'];
}
function course_registration_user_insert(&$edit, $account, $category)
{
    global $whatyear;
    global $whatfirstname;
    global $whatlastname;
    $newuserid=$account->uid;
    $yearofstudy=$whatyear;
    $fname=$whatfirstname;
    $lname=$whatlastname;
    //now use vars
    drupal_set_message('dear '.$fname.' '.$lname.' ,'.'account uid is '.$account->uid); 
}
?>

如果这不起作用,请确保以正确的顺序在同一个php实例中调用这些函数。如果在一个页面上调用第一个,然后在另一个页面上调用insert,则将打开一个新的php副本,您将丢失环境变量。