2013-05-11 75 views
-1

我看着堆栈上的流程讨论Can't access global variable inside function如何从php函数中访问全局变量?

它解决了这个问题。但我无法让代码工作。我可以尝试从函数ConvertCsvFile访问$ batch_fl_str和$ batch_str,但我无法访问这两个变量。

有什么建议吗?这里是我的代码:

$today = date(ymd); 
$curr_time = date(Hi); 
$local_time = localtime(); 
$curr_min = str_pad($local_time[1], 2, '0', STR_PAD_LEFT); 
$curr_hr = str_pad($local_time[2], 2, '0', STR_PAD_LEFT); 
$batch_fl_str = "-" . $today . "-" . $curr_hr . $curr_min; 
$batch_str = $today . "-" . $curr_hr . $curr_min ; 


function ConvertCsvFile($input_path, $input_file, $input_hist_path, $hdl_output_fl, $hdl_out_hist_fl) { 

// Define static variable 

    global $batch_fl_str; 
    global $batch_str; 
    static $fl_no = 0;  //NOTE: static variable 

    $fl_no++; 
    $fl_no_str = str_pad($fl_no, 3, 0, STR_PAD_LEFT); 
    $batch_fl_id = $batch_fl_str . "-" . $fl_no_str . "." ; 
    $batch_id = $batch_str . "-" . $fl_no_str . "-"; 
    echo "Batch fl str = $batch_fl_str \n"; 
    echo "Batch str  = $batch_str \n"; 
    echo "Batch file id = $batch_fl_id \n"; 
    echo "Batch id  = $batch_id \n"; 

}

当运行上面的程序,我收到以下输出:

Converting the file: DOC#9553814.CSV 
Batch fl str = -130511-0316 
Batch str  = 130511-0316 
Batch fl str = 
Batch str  = 
Batch file id = -001. 
Batch id  = -001- 

回答

0

您也可以访问使用$GLOBALS阵列全局变量。

例如

 $foo = 'Hello World!'; 

     function Hello() { 
      echo $GLOBALS['foo']; 
     } 

在你的代码,测试以查看是否值在变量设定的功能之外,在全球范围内它的自我。它可能是变量值没有正确分配。