我在流程讨论Can't access global variable inside function上查看了堆栈。
它解决了这个问题。但我无法让代码工作。我试图从函数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 :(得分:0)
您还可以使用$GLOBALS
数组访问全局变量。
例如
$foo = 'Hello World!';
function Hello() {
echo $GLOBALS['foo'];
}
在您的代码中,测试是否在全局范围内的函数外部的变量中设置值。可能没有正确分配变量值。