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.
Running the program confirms that the file is closed after being written.
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.