PHP变量输入/输出一个函数

I want to write data in a csv.

For that I call a function to fill it. I don't know how to call the variable outside the function (without global) so i open the file in it, but i need to close it outside, and i can't have my $fileOpen variable:

function doMyCode($args)
{
   if (!isset($firstLoop)){
     $fileOpen = fopen('customers.csv', 'w');
     $firstLoop = true;
   }
[...]
     fputcsv($fileOpen, $rowData, ";");
}
fclose($fileOpen);

So, how can i do that? With good manners, i don't want to put one looper's counter (like $i)

UPDATE

The call to the function is in Magento, it's like the array_map(), but in this form i don't know how to send another parameter or return anything:

Mage::getSingleton('core/resource_iterator')->walk(
    $theList->getSelect()->limit(10),
    array('exportClient')
);

This is the reason I have this doubt

The best way would be to handle the file opening and closeing outside

function doMyCode($args, $fileOpen ){
  fputcsv($fileOpen, $args, ";");
}

$fileOpen = fopen('customers.csv', 'w');

foreach( $lines as $line ){
  doMyCode($line , $fileOpen );
}

fclose($fileOpen);

I would not open the file inside the function and close it elsewhere, either open / close it inside that function or open / close it outside, otherwise it just gets too messy, is it open? is it closed? who knows....