Defer in PHP
In PHP, there isn’t a direct equivalent to the defer
keyword. However, we can achieve similar functionality using try-finally blocks or register_shutdown_function(). For this example, we’ll use try-finally blocks to mimic the defer behavior.
Our example will create a file, write to it, and then close it, ensuring that the file is closed even if an exception occurs.
<?php
// Suppose we wanted to create a file, write to it,
// and then close when we're done. Here's how we could
// do that with try-finally.
function main() {
$f = createFile("/tmp/defer.txt");
try {
writeFile($f);
} finally {
closeFile($f);
}
}
function createFile($p) {
echo "creating\n";
$f = fopen($p, 'w');
if ($f === false) {
throw new Exception("Unable to create file");
}
return $f;
}
function writeFile($f) {
echo "writing\n";
fwrite($f, "data\n");
}
// It's important to check for errors when closing a
// file, even in a finally block.
function closeFile($f) {
echo "closing\n";
if (!fclose($f)) {
fprintf(STDERR, "error: Unable to close file\n");
exit(1);
}
}
main();
Running the program confirms that the file is closed after being written.
$ php defer.php
creating
writing
closing
In this PHP version:
We use a try-finally block in the
main()
function to ensure thatcloseFile()
is called even if an exception occurs inwriteFile()
.The
createFile()
function now usesfopen()
to create the file and returns the file handle.writeFile()
usesfwrite()
to write to the file.closeFile()
usesfclose()
to close the file and checks for errors.We use
echo
instead offmt.Println()
for output, andfprintf(STDERR, ...)
instead offmt.Fprintf(os.Stderr, ...)
for error output.Instead of using
panic()
, we throw exceptions.We use
exit(1)
instead ofos.Exit(1)
to terminate the program with an error status.
This approach ensures that resources are properly cleaned up, mimicking the behavior of defer
in the original example.