-1

I looked at the stack over flow discussion Can't access global variable inside function.

It address this question. But I could not get the code to work. I ma trying to access $batch_fl_str and $batch_str from within the function ConvertCsvFile but I can not access the two variables.

Any suggestions? Here is my code:

$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";

}

When the above program is run, I receive the following output:

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-
Community
  • 1
  • 1

1 Answers1

0

You can also access global variables using $GLOBALS array.

for example

      $foo = 'Hello World!';

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

In your code, test to see if the values are set in the variables outside of the function in the global scope it self. it maybe that variable values are not assigned properly.

DevZer0
  • 13,433
  • 7
  • 27
  • 51