Why fopen doesn't work in anonymous function (Closure)?

Viewed 25

I don't understand why this code works :

$file = fopen('/opt/test.csv', 'w'); 
fclose($file);

while this code doesn't work :

$callback = function() use($elements, $columns) {
    $file = fopen('/opt/test.csv', 'w');
    fclose($file);
};

No error but it does not save the file in the repository. Have you an idea ?

Thank you !

1 Answers

I am unable to replicate the failure to write to a file using essentially the same code as above. Added some fwrite calls to indicate success of callback and prove file creation was successful.

$filepath=__DIR__ . '/test.csv';

$elements=array('Carbon','Nitrogen','Oxygen');
$columns=array('corinthian','doric','ionic','tuscan','egyptian','aeolic','persian');

$callback = function() use( $elements, $columns ) {
    global $filepath;
    
    $file = fopen( $filepath, 'w' );
    fwrite( $file, implode(',', $elements ) . PHP_EOL );
    fwrite( $file, implode(',', $columns ) . PHP_EOL );
    fclose( $file );
};

call_user_func( $callback, $elements, $columns );

The above works OK and yields a CSV file, in the same directory as the running script, with the following content:

Carbon,Nitrogen,Oxygen
corinthian,doric,ionic,tuscan,egyptian,aeolic,persian
Related