-1

我查看了堆栈溢出讨论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-
4

1 回答 1

0

您还可以使用$GLOBALS数组访问全局变量。

例如

      $foo = 'Hello World!';

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

在您的代码中,测试是否在其自身的全局范围内的函数外部的变量中设置了这些值。可能没有正确分配变量值。

于 2013-05-11T00:49:04.093 回答