What are the advantages and disadvantages of reusing file handles in PHP scripts for efficiency?

When working with file handles in PHP scripts, reusing them can improve efficiency by reducing the overhead of opening and closing files multiple times. However, there are also potential drawbacks such as increased complexity in managing the state of the file handle and potential issues with file locking when multiple processes are involved.

// Example of reusing file handles in PHP scripts for efficiency

$filename = "example.txt";

// Open the file handle for reading
$fileHandle = fopen($filename, "r");

// Read the contents of the file
$content = fread($fileHandle, filesize($filename));
echo $content;

// Close the file handle
fclose($fileHandle);

// Reuse the same file handle for writing
$fileHandle = fopen($filename, "w");

// Write new content to the file
fwrite($fileHandle, "New content");

// Close the file handle
fclose($fileHandle);