我看了堆栈溢出流的讨论,不能访问全局变量内部的函数。
它解决了这个问题。但我无法让代码工作。我试图访问$batch_fl_str和$batch_str从函数ConvertCsvFile,但我不能访问这两个变量。
有什么建议吗?下面是我的代码:
$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-
您也可以使用$GLOBALS
数组访问全局变量。
例如
$foo = 'Hello World!';
function Hello() {
echo $GLOBALS['foo'];
}
在你的代码中,测试一下这些值是否在函数外部的变量中设置了。也许变量值没有被正确地赋值。